使用 NSFetchedResultsController 时,CoreData 与 UITableView 有什么关系?

How is CoreData related to UITableView when using NSFetchedResultsController?

你肯定遇到了这个错误:

CoreData: error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. Invalid update: invalid number of sections. The number of sections contained in the table view after the update (8) must be equal to the number of sections contained in the table view before the update (8), plus or minus the number of sections inserted or deleted (1 inserted, 0 deleted). with userInfo (null)

这条消息对我来说没有意义,因为 CoreData 与 NSFetchedResultsController 有关,但 CoreData 与 table 视图无关。 (如果我错了纠正我) 我理解的方式是,当我们使用 controller(didChangeObject:) 控制器(didChangeSection:)

iOS 框架怎么可能知道 tableView 部分的数量,甚至不是强制性的(建议但不是强制性的)使用 UITableView ... 它应该只能检查 NSFetchedResultsController 结果 fetchedObjects 结果数组,而不是 tableview.

通常,控制器的委托是通过以下方式实现的(摘自 Apple 的核心数据编程指南):

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [[self tableView] endUpdates];
}

tableView 收到 endUpdates 消息时,它会做两件在我们的上下文中很重要的事情:

  1. 计算自 beginUpdates 以来插入和/或删除了多少节(通过使用 insertSections:withRowAnimation 方法)

  2. 检查这些更改是否反映在数据源中。在您的情况下,它们不是:通过在 table 视图上调用 insertSections:withRowAnimation 插入了 1 个部分,但当询问部分计数时,数据源仍然是 returns 8。这基本上就是错误消息所说的内容。

所以 table 视图发现它的状态不一致并抛出异常。

我们仍在 controllerDidChangeContent 委托方法中。我们再看一下报错信息:

An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent

因此 NSFetchedResultsControllertry 块内对其委托调用 controllerDidChangeContent 并捕获异常。然后它重新抛出它。

长话短说:NSFetchedResultsController 对 table 视图一无所知 - 它只是捕获了恰好在 UITableViewendUpdates 方法中抛出的异常。