尝试读取已解析的JSON数组时索引超出范围

时间:2017-06-27 20:50:26

标签: ios json swift uitableview

我有一个从NYTimes API读取JSON的函数 - 我尝试使用标题填充表格视图。这是功能:

func getJSON() {
    let url = NSURL(string: nyTimesURL)
    let request = NSURLRequest(url: url as! URL)
    let session = URLSession(configuration: URLSessionConfiguration.default)

    let task = session.dataTask(with: request as URLRequest) { (data, response, error) in

        if error != nil {
            print(error)
        }

        let json = JSON(data: data!)
        let results = json["results"].arrayValue

        for title in results {

            let titles = title["title"].stringValue
            print(titles)

            let count: Int = title.count
            self.numberOfStories = count

            self.headlines.append(titles)
            self.tableView.reloadData()
            print("\n\n\nHeadlines array: \(self.headlines)\n\n\n")
        }
    }
    task.resume()
}

然后作为类变量我有

var headlines = [String]()
var numberOfStories = 1

如果我对cell.textLabel进行硬编码,我可以运行该应用程序并看到headlines数组已正确填充了所有标题。但是如果我尝试将单元格标签设置为self.headlines[indexPath.row],我会得到一个超出范围崩溃的索引。我已尝试将tableView.reloadData()电话放入主线索(DispatchQueue.main.async{}),但这不是问题。

如何让头条新闻正确显示?

感谢您的帮助!

编辑:Tableview方法:

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.numberOfStories
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "JSONcell", for: indexPath) as! JSONTableViewCell

    cell.cellLabel.text = self.headlines[indexPath.row]


    return cell
}

1 个答案:

答案 0 :(得分:1)

您需要摆脱numberOfStories财产。请改用headlines.count

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return headlines.count
}

您的cellForRowAtnumberOfRowsInSection必须基于相同的数据。

请确保在reloadData内调用DispatchQueue.main.async,因为正在从后台队列中调用数据任务完成块。