Ios 尝试读取已解析JSON数组时索引超出范围
我有一个从NYTimes API读取JSON的函数——我试图用标题填充一个表视图。这就是功能:Ios 尝试读取已解析JSON数组时索引超出范围,ios,json,swift,uitableview,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 = ses
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,我可以运行应用程序并看到标题
数组正确填充了所有标题。但是如果我尝试将单元格标签设置为self.headlines[indexath.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
属性。使用标题。改为计数
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return headlines.count
}
您的单元格行数
和行数部分
必须基于相同的数据
请确保在
DispatchQueue.main.async
内部调用reloadData
,因为数据任务完成块是从后台队列调用的。您发布的任何代码都不会尝试访问数组。您实际上在哪里调用self.headlines[indexPath.row]?何时何地调用getJSON
?必须使用DispatchQueue.main.async
从数据任务完成块内部调用reloadData
。@rmaddy我添加了我的tableview方法-我调用self.headlines[indexPath.row]
在我的cellForRow
方法中设置标签。将重载数据调用放在DispatchQueue.main.async
中似乎没有什么区别。所有UI更新都必须在主队列上完成。好吧,我看到-numberOfStories
有点多余。我做了更改,现在可以使用了,谢谢!要确认,self.tableView.reloadData()
是否位于此处的正确位置(在for循环中)?我在它周围添加了DispatchQueue.main.async
,我只是想确保它在循环中。实际上对reloadData
的调用必须在for循环之后。为每个添加的项重新加载整个表是没有意义的。添加所有项目后重新加载一次。