我有一个 UITableView 填充了一个从 NSUserDefaults 读取的可变数组。我希望用户能够删除一些存在的项目。以下是特定于编辑方法的代码,这是整个文件: http: //pastebin.com/LmZMWBN9
当我单击“编辑”并删除一个项目时,应用程序崩溃并返回:
由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object”
我的具体问题是,我在这里做错了什么?
// 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
}
}