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

标签 ios json swift uitableview

我有一个从 NYTimes API 读取 JSON 的函数 - 我正在尝试用标题填充表格 View 。这是函数:

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
}

最佳答案

您需要删除您的 numberOfStories 属性。请改用 headlines.count

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

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

并且确保在 DispatchQueue.main.async 中调用 reloadData,因为数据任务完成 block 是从后台队列调用的。

关于ios - 尝试读取已解析的 JSON 数组时索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44789610/

相关文章:

ios - iOS无法设置进度条progress两次?

java - Json 可以保存对象引用还是只复制值?

swift - 如何处理转义键按下事件?

ios - 何时使用 respondsToSelector 与 objc_getClass

ios - 在 UserDefault 中删除套件

ios - 我在 MQTTkit ios 上收到了最后一条消息

python - 使用对象反序列化 json

json - 进行 json 解码时为空字段

swift - 如何使用新的 swift async/await 方法上传数据?

ios - iOS 和 Parse 的全局计数器?