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

时间:2012-10-01 16:35:20

标签: ios nsmutabledictionary

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

如果namenull

,为什么它会在此行崩溃?
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];
}

3 个答案:

答案 0 :(得分: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];
    }
}

答案 1 :(得分:2)

也许mutableCopy不是" deepMutableCopy",我的意思是,你只是枚举可变对象,但这个集合中的对象不可变(从我的评论中复制)

答案 2 :(得分:0)

创建新数组[[NSMutableArray alloc]initWithArray:[json objectForKey:@"data"]]并在for循环中使用它

,而是在[json objectForKey:@"data"]上运行,将其替换为新数组。 它应该是这样的:

NSMutableArray *tempCustomers = [[NSMutableArray alloc] init];
NSMutableArray *search = [[NSMutableArray alloc]initWithArray:[json objectForKey:@"data"]];
for (NSMutableDictionary *dict in search)
{
    if ([dict objectForKey:@"name"] == [NSNull null])
    {
        [dict setValue:@"null" forKey:@"name"];
    }
    [tempCustomers addObject:dict];
}