Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object'
.h
@property (nonatomic, strong) NSMutableArray *history;
.m
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSString *de = [[self.history objectAtIndex:indexPath.row] objectForKey:@"des"];
NSString *dest = [de stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://example.com/rm_history.php?user_id=%@&destinations=%@",self.uID,dest]];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
[self.history removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]
withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
NSLog(@"create");
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
[self.tableView reloadData];
}
设置断点以捕获错误后,它会在此行停止:
[self.history removeObjectAtIndex:indexPath.row];
对导致问题的原因有所了解吗?
答案 0 :(得分:27)
您声明history
一个NSMutableArray
不的事实意味着只能为其分配NSMutableArray
。如果您不小心,可以将不可变NSArray
分配给history
。例如,如果您将NSMutableArray
序列化为JSON,然后将其反序列化为NSMutableArray
,则会发生这种情况:您将获得NSArray
。
要避免此问题,请务必始终为history
分配您创建的NSMutableArray
或mutableCopy
NSArray
的{{1}}从代码的其他部分收到:
self.history = [[dataDictionary objectForKey:@"ds_history"] mutableCopy];
答案 1 :(得分:0)
您遇到此问题,因为NSUserDefaults始终返回不可变对象。
请从NSUserDefaults检索Mutable对象时,请参阅以下代码。
NSMutableArray *storeArray = [[defaultDefects objectForKey:@"defaultStoreDefects"] mutableCopy];
答案 2 :(得分:0)
* NSUserDefaults始终返回不可变对象*
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *history;
<强> - &GT;用于保存或存储
[userDefaults setObject:histrory forKey:@"des"];
[userDefaults synchronize];
- &gt;用于检索
history = [[userDefaults objectForKey:@"des"] mutableCopy];
答案 3 :(得分:-1)
我认为self.history
在被分配时会被NSArray
投放。
尝试以下代码:
self.history = [NSMutableArray arrayWithArray:[dataDictionary objectForKey:@"ds_history"]];