Search code examples
iosjsonios5nsmutablearray

Deep mutable seralizing iOS dictionaries / arrays


Some jSON comes from a local file that my app decomposes : {"1":{"name":"My List","list":[]}}.

I use this iOS 5.1 code to convert the entire thing into what I assume to be a deep mutable dictionary, due to the options utilized:

NSData *data = [[NSFileManager defaultManager] contentsAtPath:jSONFile];
NSMutableDictionary *mydict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error];

Given the option NSJSONReadingMutableContainers I would assume that the child array list would be fall into this category: "NSJSONReadingMutableContainers - Specifies that arrays and dictionaries are created as mutable objects." from the NSJSONSerialization Class Reference, but when I try to execute the following code:

NSMutableArray *myarray = [mydict objectForKey:@"1"] objectForKey:@"list"];
[myarray addObject:@"test"];

Execution explodes on the second line (addObject) with the following exceptions:

-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x887e840

** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x887e840'

From my SO research (1, 2, 3), it seems that the above error is generally caused when the element (dictionary / array) with which the object is attempting to be added to is not mutable. Furthermore, from my SO research (1, 2), it seems that there is no way to test if an object is indeed mutable in obj-c, and that is by design.

So I guess my question is, how can I ensure that my jSON structure is indeed 'deep' mutable upon (or immediately after) serialization? I know I can't use mutableCopy on mydict because that function is shallow. Any direction / solutions would be greatly appreciated. Thank you.


Solution

  • I have used this implementation which uses a category on nsdictionary to do a mutable deep copy and works great:

    deep mutable copy of a NSMutableDictionary

    So after you deserialize the json, you could just call mutableDeepCopy on it.

    This is what I have:

    @interface NSDictionary(Category)
    - (NSMutableDictionary *)mutableDeepCopy;
    @end
    
    @implementation NSDictionary(Category)
    - (NSMutableDictionary *)mutableDeepCopy{
        NSMutableDictionary * ret = [[NSMutableDictionary alloc]
                                 initWithCapacity:[self count]];
    
       NSMutableArray * array;
    
       for (NSString* key in [self allKeys]){
    
           if([[self objectForKey:key] respondsToSelector:@selector(mutableCopyWithZone:)]){
                array = [(NSArray *)[self objectForKey:key] mutableCopy];
               [ret setValue:array forKey:key];
           }
           else{
                [ret setValue:[self objectForKey:key] forKey:key];
    
           }
        }
    
        return ret;
    }
    
    @end