ios - 在索引处重新加载时 TableView 崩溃

标签 ios swift uitableview

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/

相关文章:

ios - CallKit com.apple.CallKit.error.calldirectorymanager 错误 1

ios - 从 SKTileMapNode 中删除特定图 block

ios - 如何将 Swift 数组转换为字符串?

ios - 如何将数据添加到 UITableViewCell 中的 TableView

objective-c - iOS 奇怪的继承错误

iphone - 自定义开关 - 是 否类型 - iPhone

iphone - 使用 Storyboard 将 Window rootViewController 替换为另一个 View Controller

ios - IOS Firebase Cloud Functions 中未收到推送通知

ios - 从 2012 : -[UITableView switchToFavImageView:]: unrecognized selector sent to instance 更新代码

ios - 根据表格 View 单元格中的内容更改 uilabel 高度