Deleting rows manually from UITableView in Xcode 6

33 views Asked by At

I have the following code written for my delete button to delete selected rows from the UITableView.

-(IBAction)deleteItems:(id)sender {

 NSArray *selectedCells = [self.autoCompleteView indexPathsForSelectedRows];
NSMutableIndexSet *indicesToDelete = [[NSMutableIndexSet alloc] init];
for (NSIndexPath *indexPath in selectedCells) {
    [indicesToDelete addIndex:indexPath.row];
}
//arrayFromPlist is NSMutableArray
[autoCompleteView beginUpdates];
[autoCompleteView deleteRowsAtIndexPaths:selectedCells withRowAnimation:UITableViewRowAnimationAutomatic];
[autoCompleteView endUpdates];
[selectedObjects removeObjectsAtIndexes:indicesToDelete];
[autoCompleteView reloadData];

[alertMsg deleteConfirmation:@"Do you want to delete these items?"];

}

Please check the image for my UITableView and the delete button. I have kept the Editing property of my UITableview to "Multiple Selection during Editing" in the storyboard.

enter image description here

I get the following error when i press the Delete button shown in the screen.

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '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, 2 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

Not sure what is my mistake in the delete button code.

1

There are 1 answers

6
matt On BEST ANSWER

One definite problem is that you are removing the cells before you have removed the corresponding data from the model. That's wrong. Always change the model first; then change the cells in such a way as to match the model.