无效更新:第0节UITableView中的行数无效

我知道这已经被问过50次,但我已经通过所有其他的答案,并没有发现任何可以解决我的问题。

无论如何,这是我的代码:

NSMutableArray *cellIndicesToBeDeleted = [[NSMutableArray alloc] init]; for (int i = 0; i < [thetableView numberOfRowsInSection:0]; i++) { NSIndexPath *p = [NSIndexPath indexPathForRow:i inSection:0]; if ([[thetableView cellForRowAtIndexPath:p] accessoryType] == UITableViewCellAccessoryCheckmark) { [cellIndicesToBeDeleted addObject:p]; [self.cellArray removeObjectAtIndex:i]; } } [thetableView deleteRowsAtIndexPaths:cellIndicesToBeDeleted withRowAnimation:UITableViewRowAnimationLeft]; [cellIndicesToBeDeleted release]; 

当我执行这个代码时,我得到这个崩溃日志:

 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).' 

有没有人看到我在做什么错了?

新的代码:

 NSMutableIndexSet *mutableIndexSet = [[NSMutableIndexSet alloc] init]; NSMutableArray *cellIndicesToBeDeleted = [[NSMutableArray alloc] init]; for (int i = 0; i < [thetableView numberOfRowsInSection:0]; i++) { NSIndexPath *p = [NSIndexPath indexPathForRow:i inSection:0]; if ([[thetableView cellForRowAtIndexPath:p] accessoryType] == UITableViewCellAccessoryCheckmark) { [cellIndicesToBeDeleted addObject:p]; [mutableIndexSet addIndex:p.row]; } } [self.cellArray removeObjectsAtIndexes:mutableIndexSet]; [thetableView deleteRowsAtIndexPaths:cellIndicesToBeDeleted withRowAnimation:UITableViewRowAnimationLeft]; [cellIndicesToBeDeleted release]; [mutableIndexSet release]; 

我觉得它必须做numberOfRowsInSection 。 我没有更新我的nsuserdefaults与更新的数据源,所以我现在做了,它完美的作品。 这是我的更新代码的方式:

 //Code to delete rows NSMutableIndexSet *mutableIndexSet = [[NSMutableIndexSet alloc] init]; NSMutableArray *cellIndicesToBeDeleted = [[NSMutableArray alloc] init]; for (int i = [thetableView numberOfRowsInSection:0] - 1; i >= 0; i--) { NSIndexPath *p = [NSIndexPath indexPathForRow:i inSection:0]; if ([[thetableView cellForRowAtIndexPath:p] accessoryType] == UITableViewCellAccessoryCheckmark) { [cellIndicesToBeDeleted addObject:p]; [mutableIndexSet addIndex:p.row]; } } [self.cellArray removeObjectsAtIndexes:mutableIndexSet]; [[NSUserDefaults standardUserDefaults] setObject:self.cellArray forKey:@"cellArray"]; [thetableView deleteRowsAtIndexPaths:cellIndicesToBeDeleted withRowAnimation:UITableViewRowAnimationLeft]; [cellIndicesToBeDeleted release]; [mutableIndexSet release]; 

删除行之前和之后,您需要添加以下内容:

 [theTableView beginUpdates]; // your code goes here [theTableView endUpdates];