1
votes

I have the code like below. I am retrieving JSON from a web server.

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);        

                                     }];

However it crashes with the following error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

Now, what I don't get is that, I am trying to setValue:forKey in dataDict, which is instantiated NSMutableDictionary, so I should be able to setValue.

2

2 Answers

4
votes

You have declared your dataDict as an NSMutableDictionary but that doesn't mean that you get a mutable dictionary from your JSON. What you could do is either instruct your JSON serializer to fetch you mutable copies (if it supports such option) or manually do this:

for (NSDictionary *dict in JSON) {

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

}
1
votes

dataDict is just a pointer, is not instantiated.

You are actually dealing with simple NSDictionary, so you cannot modify it. If you need to modify it just call mutableCopy on it. This will make you the owner of the object so, if you are not using ARC, remember to release it when you have done.