Question

I need to removeAllObjects from a NSMutableDictionary. The NSMutableDictionary is populated through a JSON response. In some cases I get a NSCFDictionary as result. I tried to do a mutableCopy to an NSMutableDictionary, but the Dictionary stays a NSCFDictionary...

How do I solve my problem and get an NSMutableDictionary out of a NSCFDitionary?

Take the JSON and store it

-(void)putImageDetails:(NSMutableDictionary *)json {
    NSMutableDictionary *tmp = [json mutableCopy]; // __NSCFDictionary removeAllObjects]: mutating method sent to immutable object'
    self.imageDetails = tmp;
}

removeAllObjects and populate them new

-(void)didLoadImageDetails {

    [self.detailData removeAllObjects];   // This does not work, as it's still a NSCFDict

    NSString *ssource = [[NSString alloc] initWithFormat:@"do%@", self.socialSource];        
    SEL functionCall = NSSelectorFromString(ssource);
    [self performSelector:functionCall];
    [self.tableView reloadData];
}

Here the debug output

Normal working case with NSMutableDictionary

Normal working case with NSMutableDictionary

Try to Tansform a NSCFDictonary to NSMutableDictionary but it does not work

the variable json and tmp are still NSCFDictonary. tmp should in my understanding be a NSMutableDitionary... (see variable view)

Try to Tansform a NSCFDictonary to NSMutableDictionary but it does not work

This will lead to the error: __NSCFDictionary removeAllObjects: mutating method sent to immutable object

Still an NSCFDictionary

Was it helpful?

Solution

You should be using NSJSONSerialization +JSONObjectWithData:options:error: to get the dictionary from your JSON data. It takes an options parameter which you should be setting to NSJSONReadingMutableContainers so that the created arrays and dictionaries from the JSON are all mutable.

Your current code is making self.imageDetails a mutable dictionary (though none of its contents are likely to be mutable), but then you are trying to mutate self.detailData. It isn't clear how these 2 are related but you should set up the mutability of the data structures when created (deserialised from the JSON).

OTHER TIPS

You have the add the NSCFDictonary objects not to assign the NSCFDictonary to NSMutableDictionary So do like following,

NSData *data =[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError * error=nil;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:responseJSON];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top