首页 > 解决方案 > NSFetchedResultsController 控制器 didChange 委托 - 断言失败

问题描述

我构建了一个表格视图,使用 FRC 来显示来自核心数据的数据。我还实现了控制器 didChange委托,以查看核心数据中的更改:

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

        switch (type) {
        case .insert:
            if indexPath != nil && (indexPath?.row)! < (controller.fetchedObjects?.count)!{
                tableView.insertRows(at: [indexPath!], with: .left)
            }
            break;

        case .update:
            if indexPath != nil && (indexPath?.row)! < (controller.fetchedObjects?.count)!{
                self.tableView.reloadRows(at: [indexPath!], with: .left)
            }
            break;

        case .delete:
            if indexPath != nil && (indexPath?.row)! < (controller.fetchedObjects?.count)!{
                self.tableView.deleteRows(at: [indexPath!], with: .left)
            }
            break;

        case .move:
            if indexPath != nil && (indexPath?.row)! < (controller.fetchedObjects?.count)!{
                print("type.move: shouldn't get in here!")
            }
            break;

        }
    }

当我运行时,我在控制台上得到了这个:

*** -[UITableView _endCellAnimationsWithContext:] CoreData 中的断言失败:错误:严重的应用程序错误。在调用 -controllerDidChangeContent: 期间,从 NSFetchedResultsController 的委托中捕获了一个异常。无效更新:第 0 节中的行数无效。更新后现有节中包含的行数(216)必须等于更新前该节中包含的行数(215),加上或减去数字从该部分插入或删除的行数(0 插入,0 删除)加上或减去移入或移出该部分的行数(0 移入,0 移出)。与用户信息(空)

虽然应用程序没有崩溃 - 但 tableview 被搞砸了并且没有显示日期。

标签: swiftuitableviewcore-datadelegatesnsfetchedresultscontroller

解决方案


我的错误是在插入更新时我提到了indexPath而不是newIndexPath ...

它应该是:

        case .insert:
        if newIndexPath != nil && (newIndexPath?.row)! < (controller.fetchedObjects?.count)!{
            tableView.insertRows(at: [newIndexPath!], with: .left)
        }
        break;

推荐阅读