删除tableview中的多个部分崩溃的行

时间:2013-12-09 19:35:21

标签: ios objective-c uitableview

如果所有笔记都在一个部分中,我可以从tableView中删除项目。 只要我将项目添加到多个部分,从其他部分删除注释会使应用程序崩溃并显示错误:

'Invalid update: invalid number of rows in section 0.  The number of rows contained in an 
existing section after the update (0) must be equal to the number of rows contained in that
 section before the update (1), plus or minus the number of rows inserted or deleted from that
 section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of
that section (0 moved in, 0 moved out).'

有谁知道原因或解决方案?

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

if (editingStyle == UITableViewCellEditingStyleDelete) {

    // Delete the row from the data source
    [self.tableView beginUpdates];
    [self.notes removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationRight ];

    [self.data writeToFile:self.path atomically:YES];
    [self.tableView endUpdates];

}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}

}

1 个答案:

答案 0 :(得分:0)

如果在cellForRowAtIndexPath中使用谓词:当您从数组中删除数据时应该使用它,因为indexPath.row与您的数组索引不匹配。 尝试类似的东西:

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [self.tableView beginUpdates];
        if (indexPath.section == 0){
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"Category =[cd] %@", @"Category 1"];
            NSArray * catArray = [self.notes filteredArrayUsingPredicate:pred];
            [self.notes removeObject:catArray[indexPath.row]]
             [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationRight ];


        } //else other section ....

        [self.data writeToFile:self.path atomically:YES];
        [self.tableView endUpdates];
    }