NSMutableDictionary中的setValue forKey崩溃

时间:2012-04-12 11:39:59

标签: objective-c ios nsmutabledictionary

我有如下代码。我正在从Web服务器检索JSON。

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
                                     {    

                                         for (NSMutableDictionary * dataDict in JSON) {


                                             if ([dataDict objectForKey:@"userPicture"])
                                             {

                                                objectForKey:@"userPicture"]);
                                                 NSURL *url = [NSURL URLWithString:[dataDict objectForKey:@"userPicture"]];
                                                 UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];     


                                                 [dataDict setValue:@"userPicture"
                                                             forKey:@"userPicture"]; 


                                             } 


                                             [messageList addObject: dataDict];
                                         }                                             

                                         [self processComplete];

                                     } 
                                    failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON)
                                     {
                                         NSLog(@"Failed: %@", error);        

                                     }];

然而,它崩溃时出现以下错误:

  

***因未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:' - [__ NSCFDictionary   setObject:forKey:]:发送到不可变对象'

的mutating方法

现在,我没有得到的是,我正在尝试setValue:forKey在dataDict中实例化NSMutableDictionary,所以我应该能够设置值。

2 个答案:

答案 0 :(得分:4)

您已将dataDict声明为NSMutableDictionary,但这并不意味着您从JSON获取可变字典。您可以做的是指示您的JSON序列化程序获取可变副本(如果它支持此类选项)或手动执行此操作:

for (NSDictionary *dict in JSON) {

    NSMutableDictionary * dataDict = [dict mutableCopy];
    // Rest of the code here...

}

答案 1 :(得分:1)

dataDict只是一个指针,没有实例化。

您实际上正在处理简单的NSDictionary,因此您无法对其进行修改。如果您需要修改它,只需在其上调用mutableCopy即可。这将使您成为对象的所有者,因此,如果您不使用ARC,请记得在完成后将其释放。