【发布时间】:2018-04-11 20:11:30
【问题描述】:
我从 API 获取 JSON 数据并将其显示在 tableView 中。当用户滚动到最后一行时,下一页将添加到当前数据中。 但是添加下一页数据时出现此错误。
[__NSArray0 objectAtIndex:]: 空 NSArray 超出范围的索引 0
func loadUser(_ currentPage:Int=1){
APIService.loadUser(currentPage, size: 100, callback: { data in
if let data = data["user"].arrayValue as [JSON]?{
self.jsonData?.append(contentsOf: data
self.tableView.reloadData()
self.hideLoadingInView(view: self.view)
}
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.jsonData?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell") as! UserTableViewCell
cell.user = self.jsonData?[indexPath.row]
if !isLoading && (indexPath.row == self.jsonData!.count - 1){
currentPage += 1
loadUser(currentPage)
}
return cell
}
【问题讨论】:
-
不要这样做。不要尝试从
cellForRowAt方法加载数据。这是一个非常非常糟糕的主意。该方法应该只做一件事——返回请求的单元格。可以按任何顺序随时请求单元格。
标签: ios swift uitableview