从TableView和coreData中删除行

use*_*509 2 core-data objective-c tableview delete-row ios

我从使用coreData对象填充的tableView中删除行时遇到一些问题.

试着这样做:

 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath{

        if (editingStyle == UITableViewCellEditingStyleDelete) {

            [self.tableView beginUpdates];

            NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
            NSLog(@"Deleting (%@)", [managedObject valueForKey:@"original_title"]);
            [self.managedObjectContext deleteObject:managedObject];
            [self.managedObjectContext save:nil];

            [self performFetch];       
            [self.tableView endUpdates];       
        }   
    }
Run Code Online (Sandbox Code Playgroud)

因此,当我单击"删除"按钮时,应用程序崩溃并显示以下日志:

    *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-2872.3/UITableView.m:1254
    2013-08-13 18:39:17.624 RR_proto[1076:a0b] *** Terminating app due to uncaught exception
 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. 
 The number of sections contained in the table view after the update (1) must be equal 
to the number of sections contained in the table view before the update (2), plus or minus
 the number of sections inserted or deleted (0 inserted, 0 deleted).'
    *** First throw call stack:
Run Code Online (Sandbox Code Playgroud)

我还尝试在[self.managedObjectContext save:nil]之后添加以下行:

[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
Run Code Online (Sandbox Code Playgroud)

但应用程序崩溃像以前一样.

还有一件事,每次我通过删除操作崩溃后再次启动应用程序时,应删除的单元格真的不见了!

如果有人可以提供帮助,那将是非常好的.我知道有很多关于类似问题的问题,我尝试了不同的东西,没有成功.谢谢!

Mar*_*n R 11

添加,删除或修改对象时,表视图由获取的结果控制器委托方法自动更新.

因此,要删除对象,只需从托管对象上下文中删除它.不要叫beginUpdates,endUpdates,deleteRowsAtIndexPathsperformFetch:

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
        [self.managedObjectContext deleteObject:managedObject];
        [self.managedObjectContext save:nil];
    }
}
Run Code Online (Sandbox Code Playgroud)