我目前正在开发一个项目,我使用 UITableView 和 NSFetchedResultsController 来存储我的数据。我面临的问题是使用部分不起作用。
我想显示为表格的实体具有以下特征:
- 频道(字符串)
- 服务器(字符串)
- 名称(字符串)
我希望有基于服务器的部分,每个部分中的行是频道。布局将如下所示:
- 服务器
1 通道 1 通道
2 - Server2
Channel3
Channel4
等。
但问题是,当我尝试在 NSFetchedResultsController 中插入/删除/更改元素时,应用程序会收到如下异常:
CoreData:错误:严重的应用程序错误。在调用 -controllerDidChangeContent: 期间,从 NSFetchedResultsController 的委托中捕获了一个异常。无效更新:无效的节数。更新后表视图中包含的节数(3)必须等于更新前表视图中包含的节数(2),加上或减去插入或删除的节数(0插入,0已删除)。与用户信息(空)
我做了一些研究,人们说这是因为 UITableViewController 委托首先触发并尝试显示当时不存在的元素/部分。我还没有找到解决方案,这就是我在这里的原因。
这是我的 NSFetchedResultsController 委托方法
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.tableView;
NSLog(@"--- Core Data noticed change");
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}
非常感谢
罗伯特