如何删除tableView单元格iOS

Eli*_*429 1 objective-c uitableview ios

我是Objective-C的新手.所以我在一节(5个单元格)中有一个包含5行的表格视图,我希望允许用户删除它们,但是当我点击删除按钮时应用程序会一直崩溃.它崩溃的原因是因为我在节中有5行而不是返回[self.myListItems count]如何在保留节中的5行的同时更正下面的代码?

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source


        [self.myListItems removeObjectAtIndex:indexPath.row];
        [self saveList];

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

错误是:断言失败 - [UITableView _endCellAnimationsWithContext:]

小智 5

在ViewDidLoad中:

self.tableView.allowsMultipleSelectionDuringEditing = NO;
Run Code Online (Sandbox Code Playgroud)

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
        [self.myListItems removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self saveList];
    }    
}
Run Code Online (Sandbox Code Playgroud)

请记住 - 如果要删除作为节中最后一项的行,则需要删除整个节(否则可能会导致节数错误并抛出此异常).

希望这可以帮助.