Error 'Invalid update: invalid number of rows in section 0' attempting to delete row in table

前端 未结 2 1481
忘了有多久
忘了有多久 2020-12-31 03:54

My code appears to run just fine but when I swipe to delete a line within my UITableView, the app crashes with the following:

Error

LittleTo

相关标签:
2条回答
  • 2020-12-31 04:07

    The number of rows in your table is [[ToDoItemSvc retrieveAllToDoItems] count]. When you delete 1 row in your table, then the number of rows in your table should be 1 less than the number of rows before deleting any rows. After you delete 1 row and call [self.tableView reloadData] the tableView checks to see how many rows there are in the table. At this point, numberOfRowsInSection will return [[ToDoItemSvc retrieveAllToDoItems] count]. This should now be 1 less than it was before you deleted a row.

    The short answer is, you need to first remove an item from your dataSource, which appears to be [ToDoItemSvc retrieveAllToDoItems] then delete a row.

    The compliment to this is when you add a row, you need to add an item to your dataSource as well.

    These changes need to happen before you call reloadData.

    Edit

    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
        // Actually remove the data from the source
        [ToDoItemSvc deleteToDoItem:[ToDoItemSvc retrieveAllToDoItems][indexPath.row]]
    
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
        [self.tableView reloadData];
    }
    

    ELI5: A teacher has five students: Alice, Bob, Charlie, Diane, and Eric. Bob's mom picks him up early from school before lunch. After lunch, the teacher takes attendance and panics because he only has four kids when the list says there should be five. Where's Bob?!

    If Bob's mom had removed his name from the list when she took him out of school then the teacher wouldn't have panicked.

    0 讨论(0)
  • 2020-12-31 04:26

    I figured it out with the help from above and some thinking.

    First, I finished the actual deleteToDoItem code

    - (ToDoItem *) deleteToDoItem: (ToDoItem *) todoitem {
    
        [ToDoItems removeObject:todoitem];
    
        return todoitem;
    }
    

    Then the code above

    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
        ToDoItem *toDoItem = [[ToDoItemSvc retrieveAllToDoItems] objectAtIndex:indexPath.row];
    
        [ToDoItemSvc deleteToDoItem:toDoItem];
        [self.tableView reloadData];
    
        NSLog(@"Removing data");
    }
    

    This runs and allows me to delete my item like I want!!

    0 讨论(0)
提交回复
热议问题