override func viewDidLoad() {
_previewView = previewView
super.viewDidLoad()
delegate = self
tableView.dataSource = self
tableView.delegate = self
let currentUser = (FIRAuth.auth()?.currentUser?.uid)!
let currentUserRef = DataService.ds.REF_USERS.child(currentUser)
let cutoff = Double((Date().timeIntervalSince1970) - 60 * 4 * 200000000)
currentUserRef.child("invitedToPosts").queryOrdered(byChild: "timestamp").queryStarting(atValue: cutoff).observe(.childAdded) { (snapshot: FIRDataSnapshot) in
let post = snapshot.key
self.posts.insert(post, at: 0)
let indexPath = IndexPath(item: 0, section: 0)
self.tableView.reloadRows(at: [indexPath], with: .fade)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let post = posts[indexPath.row]
cell.textLabel?.text = post
return cell
}
这样做的目标是获取帖子,获取帖子的键,将该键添加到 postsArray 的前面,然后仅重新加载该单元格。
当我运行应用程序时,出现错误:
*** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“尝试从更新前仅包含 0 行的第 0 部分删除第 0 行”
当我刚刚运行 tableview.reloadData()
时,代码工作正常,但会崩溃。
有什么想法为什么会发生这种情况/如何让它发挥作用吗?
最佳答案
仅当您确实希望重新加载现有行时才应使用reloadRows(at:)
。
在您发布的代码中,情况并非如此。在您的代码中,您将向数据模型添加一个新行。因此,您需要在 TableView 中插入新行,而不是重新加载现有行。
替换行:
self.tableView.reloadRows(at: [indexPath], with: .fade)
与:
self.tableView.insertRows(at: [indexPath], with: .fade)
使用reloadData
之所以有效,是因为它只是对 TableView 进行完全重新加载。您对数据模型进行什么更改并不重要。
关于ios - 在索引处重新加载时 TableView 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41819956/