Swift正确地将数组从数组添加到另一个数组?

时间:2016-11-07 18:23:54

标签: ios swift uitableview nsmutablearray

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

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

对于jsonArray

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

对于testArray

"<CustomCellSwift.Test: 0x17414df70>"

现在我是iOS Swift的新手,但我不知道我是否正确地将jsonArray插入testArray。这是我使用的代码。此外,我使用自定义的tableview,它应该显示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()
}

我这样做是否正确?为什么我的tableview有空单元格?

2 个答案:

答案 0 :(得分:0)

首先,您的网络/序列化代码不应该在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)
    }
}

我无法真正测试它,因此可能会出现一些错误,但这应该指向正确的方向。

答案 1 :(得分:0)

删除这行代码。

let testArray: NSMutableArray = []