【问题标题】:-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object-[__NSCFDictionary setObject:forKey:]:变异方法发送到不可变对象
【发布时间】:2012-10-01 16:35:19
【问题描述】:

运行以下代码时,[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];
}

【问题讨论】:

  • 也许 mutableCopy 不是“deepMutableCopy”,我的意思是,你只是枚举了可变对象,但这个集合中的对象不是可变的?
  • 您使用的是不可变对象的可变字典

标签: ios nsmutabledictionary


【解决方案1】:

我最终使用了这个。我猜这就是 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];
    }
}

【讨论】:

  • 这近似于一个深度可变副本 - 基本上,您还需要一个 dict 的可变副本,而不仅仅是 JSON 对象的数据。您尝试修改的每个字典本身都是不可变的,即使字典的原始集合通过您的mutableCopy 变得可变。 (短语“深拷贝”是指所有包含的数据结构的递归拷贝,而不仅仅是顶层。)
  • 没错。你得到一个 JSON 数据的可变副本(其中仍然有不可变的字典),然后为每个字典制作一个可变副本——这近似于一个“深度可变副本”,即使它不在单独的方法中。
【解决方案2】:

也许 mutableCopy 不是“deepMutableCopy”,我的意思是,您只是枚举可变对象,但此集合中的对象不可变(复制自我的评论)

【讨论】:

    【解决方案3】:

    创建新数组 [[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];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 2016-11-17
      • 1970-01-01
      相关资源
      最近更新 更多