当我使用以下代码从TableView中删除一行时:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
NSError *error = nil;
NSLog(@"Rows before deletion: %d", [[self.fetchedResultsController fetchedObjects] count]);
NSManagedObject *obj = [self.fetchedResultsController objectAtIndexPath:indexPath];
[self.managedContext deleteObject:obj];
NSLog(@"Rows before save: %d", [[self.fetchedResultsController fetchedObjects] count]);
if (![self.managedContext save:&error]) {
NSLog(@"Error while deleting time: %s", error.localizedDescription);
}
NSLog(@"Rows after save: %d", [[self.fetchedResultsController fetchedObjects] count]);
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
然后我得到以下错误。可能是什么原因?对象的数量每次都是相同的。为什么上下文不会获取已删除对象的此信息。不是自动的吗?
错误是删除行后的行数必须是删除/添加的行的加号或减号。
由于
答案 0 :(得分:0)
保存上下文后,您必须重新执行“更新”self.fetchedResultsController的请求。
if (![self.managedContext save:&error]) {
NSLog(@"Error while deleting time: %s", error.localizedDescription);
}
self.fetchedResultsController = ...
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
...