iOS错误"[__ NSCFArray removeObjectAtIndex:]:发送到不可变对象的mutating方法"

use*_*229 5 objective-c uitableview nsmutablearray ios

错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object'
Run Code Online (Sandbox Code Playgroud)

代码:

.h

@property (nonatomic, strong) NSMutableArray *history;
Run Code Online (Sandbox Code Playgroud)

.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];
}
Run Code Online (Sandbox Code Playgroud)

设置断点以捕获错误后,它会在此行停止:

[self.history removeObjectAtIndex:indexPath.row];
Run Code Online (Sandbox Code Playgroud)

什么导致问题的任何想法?

das*_*ght 27

您声明historya的NSMutableArray事实并不意味着只能NSMutableArray分配给它.如果你不小心,可以为你分配一个不可变NSArrayhistory.例如,如果您序列化NSMutableArray(例如)JSON,然后将其反序列化为以下内容,则会发生这种情况NSMutableArray:您将得到一个NSArray代替.

为了避免这个问题,请确保您始终分配history无论是NSMutableArray您创建的,或调用的结果mutableCopyNSArray,你从你的代码的其他部分得到:

self.history = [[dataDictionary objectForKey:@"ds_history"] mutableCopy];
Run Code Online (Sandbox Code Playgroud)