ios - Swift 将对象从一个数组正确添加到另一个数组?

标签 ios swift uitableview nsmutablearray

所以我有 2 个 NSMutableArray,一个称为 testArray,另一个称为 jsonArray。 jsonArray 使用 json 和 php 从 mysql 服务器获取其对象。然后将 jsonArray 中的相同对象插入到 testArray 中。我做了 print(jsonArray, testArray) ,日志中显示的是这个。

我还有一个名为 Test 的 NSObject 类,如果有帮助的话..

对于 jsonArray

 {
  testName = GreenCorn;
  testStatus1 = 12;
  testStatus2 = 13;
  testURL = "";
  id = 1;
 }

对于测试数组

"<CustomCellSwift.Test: 0x17414df70>"

现在我是 iOS Swift 的新手,但我不知道我是否正确地将 jsonArray 插入到 testArray 中。这是我使用的代码。另外,我正在使用自定义表格 View ,它应该显示 testArray.count、它的空单元格,但它显示我在 jsonArray 中的几行。

var followedArray: NSMutableArray = []
var testArray: NSMutableArray = []

var jsonArray: NSMutableArray = []
var filteredArray: NSArray = []

var isFiltered: Bool = false


// Number of Rows in Section
internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if !isFiltered {
        if section == 0 {
            return followedArray.count
        }
        else if section == 1 {
            return testArray.count
        }
    }
    return filteredArray.count

}


internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let CellIdentifier = "Cell"
    var cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as! CustomCell

    if cell != cell {
        cell = CustomCell(style: UITableViewCellStyle.default, reuseIdentifier: CellIdentifier)
    }

    // Coloring TableView
    myTableView.backgroundColor = UIColor.white

    // Configuring the cell
    var testObject: Test

    print("before ifFiltered")

    if !isFiltered {
        if indexPath.section == 0 {
            print("isFiltered if")
            testObject = followedArray[indexPath.row] as! Test
            cell.populateCell(testObject, isFollowed: true, indexPath: indexPath, parentView: self)
        }
        else if indexPath.section == 1 {
            print("isFiltered if 2")
            testObject = testArray[indexPath.row] as! Test
            cell.populateCell(testObject, isFollowed: false, indexPath: indexPath, parentView: self)
        }
    }
    else {
        print("isFiltered else")
        testObject = filteredArray[indexPath.row] as! Test
        cell.populateCell(testObject, isFollowed: false, indexPath: indexPath, parentView: self)
    }

    return cell
}





// Retrieving Data from Server
func retrieveData() {

    let getDataURL = "http://exampleip.org/json.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {

        let data: Data = try Data(contentsOf: url as URL)
        jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

        // Setting up testArray
        let testArray: NSMutableArray = []

        // Looping through jsonArray
        for i in 0..<jsonArray.count {

            // Create Test Object
            let tID: String = (jsonArray[i] as AnyObject).object(forKey: "id") as! String
            let tName: String = (jsonArray[i] as AnyObject).object(forKey: "testName") as! String
            let tStatus1: String = (jsonArray[i] as AnyObject).object(forKey: "testStatus1") as! String
            let tStatus2: String = (jsonArray[i] as AnyObject).object(forKey: "testStatus2") as! String
            let tURL: String = (jsonArray[i] as AnyObject).object(forKey: "testURL") as! String

            // Add Test Objects to Test Array
            testArray.add(Test(testName: tName, andTestStatus1: tStatus1, andTestStatus2: tStatus2, andTestURL: tURL, andTestID: tID))

            print("retrieveData")
            print(jsonArray, testArray)
        }

    }
    catch {
        print("Error: (Retrieving Data)")
    }

    myTableView.reloadData()
}

我这样做正确吗?为什么我的表格 View 有空单元格?

最佳答案

首先,您的网络/序列化代码不应该位于 ViewController 中,但这是一种更好的方法:

func retrieveData() {

    let getDataURL = "http://exampleip.org/json.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {

        let data: Data = try Data(contentsOf: url as URL)
        guard let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String : AnyObject]] else {
            print("Error Retrieving Data")
            return
        }

        let testArray = jsonArray.flatMap(Test.init)

        // make sure the add the result in your viewController
        self.myTableView.models = testArray
    }
    catch {
        print("Error: (Retrieving Data)")
    }

    myTableView.reloadData()
}

extension Test {

    convenience init?(with jsonDictionary: [String : AnyObject]) {
        guard let tID = jsonDictionary["id"] as? String, let tName = jsonDictionary["testName"] as? String, let tStatus1 = jsonDictionary["testStatus1"] as? String, 
              let tStatus2 = jsonDictionary["testStatus2"] as? String, let tURL = jsonDictionary["testURL"] as? String else {
            return nil
        }
        self(testName: tName, andTestStatus1: tStatus1, andTestStatus2: tStatus2, andTestURL: tURL, andTestID: tID)
    }
}

我无法真正对其进行测试,因此可能存在一些错误,但这应该会为您指明正确的方向。

关于ios - Swift 将对象从一个数组正确添加到另一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40471963/

相关文章:

ios - 使用 Objective-C 计算年龄

ios - 如何从 nsarray 的 nsarray 中搜索特定联系人

ios - Collection View 布局问题

ios - 将密码学与 ObjectMapper 结合使用

ios - TableView (_ :heightForHeaderInSection:) not working

Swift - 与 Accelerate Framework 的卷积

ios - iOS 邮件应用程序撰写屏幕是否使用 UITableView?如果是这样,为什么?

ios - UiTableView 重新加载数据后保留选定的部分/行

ios - 将 UITableView 样式更改为从代码分组但在 Xcode 中没有初始化

ios - UITableView 重新加载问题