如何使deleteRowsAtIndexPaths:使用Generic uiTableViewController?

时间:2009-06-19 03:15:31

标签: iphone objective-c cocoa-touch

我正在使用Matt Gallagher的GenericTableViewController想法来控制我的UITableViews。我的数据源是NSFetchedResultsController

http://cocoawithlove.com/2008/12/heterogeneous-cells-in.html

一切正常,直到我尝试删除一个单元格。

我在View Controller中有以下代码:

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

  if (editingStyle == UITableViewCellEditingStyleDelete) {

        // Delete the managed object.
        NSManagedObjectContext *context = [wineryController managedObjectContext];
        [context deleteObject:[wineryController objectAtIndexPath:indexPath]];

        NSError *error;
        if (![context save:&error]) {
            // Handle the error.
        }
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  }   
}

最后一行因控制台中相当冗长的解释而崩溃:

*** 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 (5) must be equal to the number  
of rows contained in that section before the update (5), plus or minus the number  
of rows inserted or deleted from that section (0 inserted, 1 deleted).'

好的,我理解它是什么意思......一行没有被删除(我会假设),因为我没有将某些消息转发到正确的地方(因为我已经将某些代码从其'正常'位置移动了)...任何人都知道哪一个?我完全被这个困扰了。

1 个答案:

答案 0 :(得分:67)

嗯,哇。我刚刚找到this回答,这不一样,但让我朝着正确的方向前进。我会留在这里给将来遇到类似麻烦的人。

关键是用开始和结束标记包装deleteRowsAtIndexPaths,并强制模型在同一个块内更新,结果是:

[tableView beginUpdates];
[self constructTableGroups];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
        withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];

这导致问题消失,动画才能完美运作。