重新加载表格 View 时,我收到错误“索引超出范围”。 如果我注释掉 tableView.reloadData 并打印数组计数,它会显示一个完整的数组,但是当我将它放在主调度队列中时,它将打印一个空数组并导致错误。
func loadData () {
posts = [CKRecord] ()
print("loading")
var predicate : NSPredicate!
predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
let publicData = CKContainer.default().publicCloudDatabase
let queryPic = CKQuery(recordType: "Main", predicate: predicate)
publicData.perform(queryPic, inZoneWith: nil) { (results:[CKRecord]?, error:Error?) -> Void in
print(results?.count as Any)
//prints full array here
if let Pics = results {
self.posts = Pics
DispatchQueue.main.sync{
//Commenting out below prints a full array
self.tableView.reloadData()
self.refresh.endRefreshing()
print(results?.count as Any)
// full array also prints here when reloadData is removed.
print("refreshed pics")
}
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let varCount = posts.count as Int
print(varCount)
let post = posts[indexPath.row]
let cellPic = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! StreamTableViewCell
if let postContent = post["content"] as? String {
let postImage = post["picture"] as? CKAsset
let data = try? Data(contentsOf: (postImage?.fileURL)!)
let name = post["UserID"] as? String
let vote = post["voteInteger"] as! Int
cellPic.layer.cornerRadius = 8.0
cellPic.layer.masksToBounds = true
cellPic.delegate = self
cellPic.streamImageView.image = UIImage(data: data! )
cellPic.nameLabel.text = name
cellPic.contentLabel.text = postContent
cellPic.voteInteger.text = String(describing: vote)
cellPic.voteOld = vote
cellPic.recordName = post.recordID.recordName
}
return cellPic
这是调试器读数-
loading
Optional(3)
Optional(3)
refreshed pics
3
3
loading
0
fatal error: Index out of range
2017-10-07 17:51:36.345951-0400 PondrMatchv.2[2910:357829] fatal error:
Index out of range
如您所见,应用程序启动时加载正常,数组包含 3 条记录,并且重新加载时不会改变。
此外,如果数组中只有一条记录,它将完全正常地重新加载。我最近更改了 Cloudkit 容器名称,但即使我切换回旧容器,它也会崩溃。这也会发生在生产容器中。
更新:这是部分函数中的行数。
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
此外,在添加断点并使用调试器读数重新确认后,重新加载时似乎会跳过整个调度调用,并直接进入 tableview cellForRowAt 函数,这就是为什么我没有得到两个 Optional(3)
打印。
最佳答案
通过更改谓词解决了问题。不确定快速更新是否存在错误或什么。
关于ios - tableView.reloadData 清除数组 - 索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46625573/