删除行时崩溃

时间:2012-05-30 10:02:07

标签: iphone objective-c ios xcode uitableview

在我的表视图类中使用以下方法,我试图删除表视图的一行

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arrUserData count];
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:YES];   
}

- (void)tableView:(UITableView *)tv commitEditingStyle (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if(editingStyle == UITableViewCellEditingStyleDelete) 
    {
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [arrUserData removeObjectAtIndex:indexPath.row];
    }
}

并且我在表格中有大约40行,当我点击其在此行崩溃的任何行上的红色删除按钮时

[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

使用以下崩溃日志

2012-05-30 14:58:45.835 testDeleteRow[3276:207] *** 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 (41) must be equal to the number of rows contained in that section before the update (41), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted).'

任何人都可以告诉我如何解决这个问题,而不是提前

2 个答案:

答案 0 :(得分:1)

实际上,在删除cells时需要更新数据源。如果您使用array填充table,那么在此行之后 -

[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

您需要从index移除同一array的对象。此外,section中的行数应减少1.如果您在那里返回array计数,则会自动处理。

答案 1 :(得分:0)

当您从tableview中删除行时,您的数据源不会更新。如果您的表在删除前包含10行,那么删除后它将只包含9行,而您的数据源仍包含10个值。所以您必须明确地从数据源中删除已删除的值。

相关问题