在UITableView中插入和删除行有时会导致崩溃?

kid*_*d49 4 objective-c uitableview uiviewanimation ios

我做的很平常.首先修改数据模型,然后更新TableView.但有时应用程序崩溃.并抛出类似的错误(取决于插入或删除).

Fatal Exception: NSInternalInconsistencyException
Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (10) must be equal to the number of rows contained in that section before the update (10), 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).
Run Code Online (Sandbox Code Playgroud)

这是我的插入代码.

[self.tableView beginUpdates];
[self.stories insertObject:story atIndex:0];
NSArray *indexPaths = @[[NSIndexPath indexPathForRow:0 inSection:0]];
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
Run Code Online (Sandbox Code Playgroud)

和删除代码.

[tableview beginUpdates];
[stories removeObject:story];
NSIndexPath *indexpath = [tableview indexPathForCell:cell];
if(indexpath) {
    [tableview deleteRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationTop];
}
[tableview endUpdates];
Run Code Online (Sandbox Code Playgroud)

Hem*_*ang 6

插入代码:

[self.stories insertObject:story atIndex:0];

[self.tableView beginUpdates];
NSArray *indexPaths = @[[NSIndexPath indexPathForRow:0 inSection:0]];
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
Run Code Online (Sandbox Code Playgroud)

删除代码:

[stories removeObject:story];

[tableview beginUpdates];
NSIndexPath *indexpath = [tableview indexPathForCell:cell];
[tableview deleteRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationTop];
[tableview endUpdates];
Run Code Online (Sandbox Code Playgroud)

注意:在更新tableview的行内部时,不应向对象添加/删除对象.