Reputation: 25
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:]
Upvotes: 1
Views: 4889
Reputation: 861
Try to use these:
[self.myListItems removeObjectAtIndex:indexPath.row];
[tableView beginUpdate];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
[self saveList];
Upvotes: 0
Reputation: 1112
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];
}
Upvotes: 0
Reputation: 584
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.
Upvotes: 5