1

I'm new to Objective-C. So I have a Table View with 5 rows in the section (5 cells), and I want to allow the user to delete them, but the app keeps crashing when I click on the delete button. The reason it crashes is because I have 5 rows in the section instead of returning [self.myListItems count] How do I correct this code below while keeping the 5 rows in the section?

- (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];
    }
}

The error is: Assertion failure in -[UITableView _endCellAnimationsWithContext:]

Bhumit Mehta
  • 16,278
  • 11
  • 50
  • 64
Elizabeth429
  • 25
  • 1
  • 7

3 Answers3

5

In ViewDidLoad:

self.tableView.allowsMultipleSelectionDuringEditing = NO;

And

- (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];
    }    
}

Remember - If you want to remove a row that is the last item in a section you need to remove the whole section instead (otherwise it might get section count wrong and throw this exception).

Hope this helps.

Satish A
  • 584
  • 4
  • 17
0

Try to use these:

[self.myListItems removeObjectAtIndex:indexPath.row];

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

[self saveList];
Harjot Singh
  • 6,767
  • 2
  • 38
  • 34
Konstantin
  • 861
  • 4
  • 12
0

change the following lines

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView beginUpdates]
 [self.myListItems removeObjectAtIndex:indexPath.row];
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 [tableView endUpdate];
 [self saveList];
}
Amit Jagesha シ
  • 1,092
  • 12
  • 21