尝试从UITableView中删除单元格时出错

时间:2012-08-02 19:36:08

标签: objective-c ios

当我尝试从我的UITableView中移除一个单元格时,它给了我这个错误:

*** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1912.3/UITableView.m:1046 2012-08-02 16:35:13.941 jsontest2[1551:f803] *** 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 (4) must be equal to the number of rows contained in that section before the update (4), 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).' *** First throw call stack: (0x13e0052 0x1571d0a 0x1388a78 0x9c02db 0xbb518 0xc6211 0xc623f 0x2ce9 0xd289d 0x226d70 0x13e1ec9 0x3a5c2 0x3a55a 0xdfb76 0xe003f 0xdf2fe 0x5fa30 0x5fc56 0x46384 0x39aa9 0x12cafa9 0x13b41c5 0x1319022 0x131790a 0x1316db4 0x1316ccb 0x12c9879 0x12c993e 0x37a9b 0x1c22 0x1b95) terminate called throwing an exception**

这是我的代码:

- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath 
{
    [tabela beginUpdates]; 
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        // Get the TAG and ID of Bill to delete
        //UITableViewCell * cell = [self tableView:tabela cellForRowAtIndexPath:indexPath];
        //NSLog(@"%d", cell.tag);

        [tabela deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:YES];      

    }   

    [tabela endUpdates];
    [tabela reloadData];

}

感谢您的帮助!

修改

self.billsArray = [[NSMutableArray alloc] init];
self.billsArray = [resultsDictionary objectForKey:@"bills"];

2 个答案:

答案 0 :(得分:5)

在billsArray中,确保并删除正在删除的相应对象。

[billsArray removeObjectAtIndex:indexPath.row];

以下是输出中的提示:

  

更新后现有部分中包含的行数   (4)必须等于该部分中包含的行数   在更新(4)之前,加上或减去插入的行数或   从该部分删除(0插入,1删除)和加号或减号   移入或移出该部分的行数

所以你的UITableView几乎是在说:

  

“好的,我有20行(来自[billsArray计数]。现在我是   假设删除一行,这意味着我应该有19行   总......但我的代表说我应该有20排...... Whhhattt   dooo我dooo ??? .....崩溃“ - UITableView

因此,每当删除行时,请确保从数据数组中删除对象。 OR 如果添加一行,请确保将其添加到数据阵列中。

编辑: (响应OP编辑)。

有你的问题。

self.billsArray = [resultsDictionary objectForKey:@"bills"]; 

这会创建一个只读数组。

您需要做的是:

self.billsArray = [[NSMutableArray alloc] initWithArray:[resultsDictionary objectForKey:@"bills"]];

或者

self.billsArray = [NSMutableArray arrayWithArray:[resultsDictionary objectForKey:@"bills"]];

或者你可以做(​​不是干净的方法):

NSMutableArray *temp = [resultsDictionary objectForKey:@"bills"];
self.billsArray = [temp mutableCopy];

答案 1 :(得分:0)

如果您的表只有一个部分,您可以在方法中的某处调用[billsArray removeObjectAtIndex:[indexPath row]],假设billsArray是NSMutableArray,而不是NSArray。如果不是,您可以将其更改为一个,或将其内容复制到新的NSMutableArray,然后将该数组用作表数据源。