【发布时间】:2023-03-30 00:25:01
【问题描述】:
我有一个基于 Core Data 的表视图,它有一个简单的删除方法。这是可以在无数教程中找到的简单代码,但是,它会使应用程序崩溃并显示以下消息:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (2), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
删除方法如下:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// get garden to delete, delete it through Core Data
Garden *gardenToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSLog(@"Garden name: %@", gardenToDelete.gardenName);
[self.managedObjectContext deleteObject:gardenToDelete];
[self.managedObjectContext save:nil];
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
[self.tableView endUpdates];
}
}
我花了几个小时重新排列代码,删除 beginUpdate 和 endUpdate 调用,检查其他解决方案。非常感谢您的帮助。
【问题讨论】:
-
什么是self.fetchedResultsController和self.managedObjectContext?
-
视图的核心数据栈对象
标签: ios objective-c cocoa-touch uitableview core-data