简体   繁体   中英

How to delete multiple sections in table view in objective c?

When I try to delete multiple sections I am getting this error.

Terminating app due to uncaught exception

'NSInternalInconsistencyException', reason: 'attempt to delete section 5, but there are only 4 sections before the update'

Here is my code:

NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];

int i=0;

for (NSIndexPath *selectionIndex in selectedRows){


    NSManagedObjectContext *context = [self managedObjectContext];

    NSManagedObject *managedObject = [arrayToDelete objectAtIndex:i];
    [self.devices removeObject:[arrayToDelete objectAtIndex:i++]];
    [context deleteObject:managedObject];
    [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:selectionIndex.section] withRowAnimation:UITableViewRowAnimationFade];
}


[self saveContext];

[arrayToDelete removeAllObjects];

I would suggest to inverse direction when you try to remove something in array. that is:

//int i=0;

for (int i = [selectedRows count] - 1; i = 0; i-- ){

NSIndexPath *selectionIndex = selectedRows[i];
    NSManagedObjectContext *context = [self managedObjectContext];

    NSManagedObject *managedObject = [arrayToDelete objectAtIndex:i];
    [self.devices removeObject:[arrayToDelete objectAtIndex:i]];
    [context deleteObject:managedObject];
    [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:selectionIndex.section] withRowAnimation:UITableViewRowAnimationFade];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM