- [__ NSCFDictionary setObject:forKey:]:将mutating方法发送到不可变对象

Bot*_*Bot 4 nsmutabledictionary ios

运行以下代码时,[dict setValue:@"null" forKey:@"name"];不断崩溃.我在这里搜索,发现其他帖子是由不使用的人引起的NSMutableDictionary.但是我正在使用它.

为什么这条线崩溃,如果name是null?

NSMutableArray *tempCustomers = [[NSMutableArray alloc] init];
for (NSMutableDictionary *dict in [[json objectForKey:@"data"] mutableCopy]) {
    if ([dict objectForKey:@"name"] == [NSNull null]) {
        [dict setValue:@"null" forKey:@"name"];
    }
    [tempCustomers addObject:dict];
}
Run Code Online (Sandbox Code Playgroud)

Bot*_*Bot 15

我最终使用了这个.我猜这是一个deepMutableCopy是什么?

NSMutableArray *tempCustomers = [[NSMutableArray alloc] init];
for (NSMutableDictionary *dict in [[json objectForKey:@"data"] mutableCopy]) {
    if ([dict objectForKey:@"name"] == [NSNull null]) {
        NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
        tempDict = [dict mutableCopy];

        [tempDict setValue:@"null" forKey:@"name"];
        [tempCustomers addObject:tempDict];
    } else {
        [tempCustomers addObject:dict];
    }
}
Run Code Online (Sandbox Code Playgroud)