错误:

编码:.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];
对导致问题的原因有任何想法吗?

最佳答案

您将history声明为NSMutableArray的事实并不意味着只能将NSMutableArray分配给它。如果您不小心,可以将一个不变的NSArray分配给history。例如,如果将NSMutableArray序列化为JSON,然后反序列化回NSMutableArray,就会发生这种情况:您将得到一个NSArray

为避免此问题,请确保始终为history分配创建的NSMutableArray,或分配对从代码其他部分收到的mutableCopy调用NSArray的结果:

self.history = [[dataDictionary objectForKey:@"ds_history"] mutableCopy];

关于iOS错误 "[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22381384/

10-14 22:05