首页 > 解决方案 > Swift - 帮助解决崩溃“无效更新:第 0 部分中的无效行数” - 具体案例

问题描述

我有一个应用程序崩溃的问题(我无法从中重新创建,但我有错误消息)。我想我知道导致它的一般区域,但无法确定它。确切的崩溃消息如下:

致命异常:NSInternalInconsistencyException - 无效更新:第 0 节中的行数无效。更新后现有节中包含的行数 (8) 必须等于更新前该节中包含的行数 (10),加上或减去从该节插入或删除的行数(0 插入,1 删除),加上或减去移入或移出该节的行数(0 移入,0 移出)。

这个确切的错误已经发生了多次。此问题与堆栈溢出的其他类似问题之间的区别在于,在导致问题的更新(删除)之后,似乎比原始(10)行少了 2 行。

对于我所看到的所有问题,都涉及之前和之后的行数相等,例如删除之前的 5 行和删除之后的 5 行。但在这种情况下,它在 1 次删除后下降了 2 行。

解决此问题的通常建议是在删除 tableview 单元格之前更改数据数组,但这不是问题,如下面的代码所示。

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
     guard let section = self.sections?[indexPath.section],
     let product = section.products?[indexPath.row] else { return nil }
     let delete = UITableViewRowAction(style: .default, title: 
     "ActionText") { 
     [weak self] (action, indexPath) in
           self?.remove(product: product, in: section, at: indexPath)
     }
     return [delete]
}

func remove(product: BasketProduct, in section: BasketTableViewSection, at indexPath: IndexPath) {

    self.tableView.beginUpdates()
    guard let basket = self.basket, let index = 
    basket.products.firstIndex(where: { $0==product }) else { return }
    basket.products.remove(at: index)
    self.basket = basket

//Some code happens here that saves the changes to the data(basket) array 
// to a database but I won't show as it is unimportant.

    if section.products?.count == 1 {
        self.tableView.deleteSections(IndexSet(integer: 
        indexPath.section), with: .right)
    } else {
        tableView.deleteRows(at: [indexPath], with: .right)
    }

    self.updateBasket(reconfigureView: false) 
    { [weak self] in

        UIView.runOnMainThread {
             self?.tableView.endUpdates()
        }

}

*** "updateBasket" 的定义相当长,所以被省略了。值得一提的是,它里面有一个 tableView.reloadData 方法。

有没有什么看起来可能会导致这样的错误的东西?如果可能是正确方向的指针?这个特定错误的解决方法通常是什么?

标签: swiftuitableview

解决方案


推荐阅读