Reputation: 774
I have problem with deleting rows from my tableView
, because I have multiple sections that are dynamically generated when view controller appears, so when I return the count in numberOfRowsInSection
it ends up looking like this:
NSInteger count = [[_sectionsArray objectAtIndex:section] count];
return count;
Now when deleting I generate this same type of array like this:
NSMutableArray *contentsOfSection = [[_sectionsArray objectAtIndex:[indexPath section]] mutableCopy];
[contentsOfSection removeObjectAtIndex:[indexPath row]];
As you can see I'm deleting the object from an array that is not linked to the tableView
, so it just returns an NSInternalInconsistencyException
Can anybody help me with this?
UPDATE:
[contentsOfSection removeObjectAtIndex:[pathToCell row]];
if ([contentsOfSection count] != 0) {
// THIS DOESN'T
[self.tableView deleteRowsAtIndexPaths:@[pathToCell] withRowAnimation:UITableViewRowAnimationFade];
}
else {
// THIS WORKS!
[_sectionsArray removeObjectAtIndex:[pathToCell section]];
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:[pathToCell section]] withRowAnimation:UITableViewRowAnimationFade];
}
Upvotes: 0
Views: 1040
Reputation: 1305
In following code :
[_sectionsArray removeObjectAtIndex:[pathToCell section]];
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:[pathToCell section]] withRowAnimation:UITableViewRowAnimationFade];
You are deleting object from _sectionArray. So this array automatically updates. But in other cases you are creating another copy and then deleting object from that array. So your _sectionArray is not going to update. So this is necessary that after deleting object from copy array, update section array with that new array also.
NSMutableArray *contentsOfSection = [[_sectionsArray objectAtIndex:[indexPath section]] mutableCopy];
[contentsOfSection removeObjectAtIndex:[indexPath row]];
[_sectionsArray replaceObjectAtIndex:[indexPath section] withObject:contentsOfSection];
Try this one and I hope that this will work.
Upvotes: 0
Reputation: 42987
muatableCopy will create another instance of the array. So you are removing item from the newly created array not from the old one. Always store 'contentsOfSection ' as a mutable array in _sectionsArray. Then remove like this.
NSMutableArray *contentsOfSection = [_sectionsArray objectAtIndex:[indexPath section]];
[contentsOfSection removeObjectAtIndex:[pathToCell row]];
if ([contentsOfSection count] != 0) {
[self.tableView deleteRowsAtIndexPaths:@[pathToCell] withRowAnimation:UITableViewRowAnimationFade];
}
else {
// THIS WORKS!
[_sectionsArray removeObjectAtIndex:[pathToCell section]];
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:[pathToCell section]] withRowAnimation:UITableViewRowAnimationFade];
}
Upvotes: 1