Reputation: 315
I have a UITableView populated with a mutablearray that is read from NSUserDefaults. I want the user to be able to remove some of the items present. Below is the code specific to the editing method and here is the whole file: http://pastebin.com/LmZMWBN9
When I click "edit" and remove an item the application crashes and I get back:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object'
My specific question is, what am I doing incorrectly here?
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// edit list of names
if ([listOfNames count] >= 1) {
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[listOfNames removeObjectAtIndex:[indexPath row]];
// write updated listofnames to nsuserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[[NSUserDefaults standardUserDefaults] setObject:listOfNames forKey:@"My Key"];
[defaults synchronize];
if ([listOfNames count] == 0) {
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
[tableView endUpdates];
}
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
Upvotes: 1
Views: 170
Reputation: 15213
Your listOfNames
instance variable is immutable, therefore you can't remove objects from it.
Change:
listOfNames = [[defaults objectForKey:@"My Key"] copy];
to
listOfNames = [[defaults objectForKey:@"My Key"] mutableCopy];
in your -viewWillAppear:
and viewDidLoad
methods.
Upvotes: 3