我已经阅读了有关此的所有相关帖子,但我仍有错误:

'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (5), 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).'

这是细节:

.h我有一个NSMutableArray

@property (strong,nonatomic) NSMutableArray *currentCart;

.m我的numberOfRowsInSection看起来像这样:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.


    return ([currentCart count]);

}

启用删除并从数组中删除对象:

// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //when delete is tapped
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

        [currentCart removeObjectAtIndex:indexPath.row];


    }
}

我认为,通过将我的部分数量依赖于我正在编辑的数组的数量,它将确保行数适当数量?无论如何,当您删除一行时,不必重新加载桌子吗?

答案

您需要从数据数组中删除对象 你打电话deleteRowsAtIndexPaths:withRowAnimation:

// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //when delete is tapped
        [currentCart removeObjectAtIndex:indexPath.row];

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

您还可以使用阵列创建快捷方式来简化代码@[]

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

来自: stackoverflow.com