'无效更新:第0部分中的行数无效

use*_*646 63 arrays objective-c nsmutablearray ios

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

'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).'
Run Code Online (Sandbox Code Playgroud)

以下是详细信息:

.h我有一个NSMutableArray:

@property (strong,nonatomic) NSMutableArray *currentCart;
Run Code Online (Sandbox Code Playgroud)

.mnumberOfRowsInSection看起来像这样:

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


    return ([currentCart count]);

}
Run Code Online (Sandbox Code Playgroud)

要启用删除并从阵列中删除对象:

// 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];


    }
}
Run Code Online (Sandbox Code Playgroud)

我认为通过让我的部分数量依赖于我正在编辑的数组的数量,它将确保适当的行数?无论如何,当你删除一行时不必重新加载表就不能这样做吗?

Und*_*ndo 147

调用之前,需要从数据数组中删除该对象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];
    }
}
Run Code Online (Sandbox Code Playgroud)

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

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
Run Code Online (Sandbox Code Playgroud)


小智 8

Swift版本->在调用之前从数据数组中删除对象

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        print("Deleted")

        currentCart.remove(at: indexPath.row) //Remove element from your array 
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}
Run Code Online (Sandbox Code Playgroud)


Has*_*bal 6

就我而言,问题是numberOfRowsInSection在调用tableView.deleteRows(...).

由于在我的情况下这是必需的行为,因此我最终调用tableView.reloadData()而不是删除行后将保持不变的tableView.deleteRows(...)情况numberOfRowsInSection