Sunday, April 21, 2013

Using dot notation with NSDictonary

NSDictionary+DotPath provides support for accessing and mutating nested dictionary values using dot notation. 

Given NSDictionary* dict:

dict = {
    int = 0;
    dictLevel1 =     {
        int = 1;
        dictLevel2 =         {
            int = 2;
        };
    };
}


Values can be accessed using a dot notation for the path e.g.
int i = [dict intForPath:@"dictLevel1.dictLevel2.int"]; // i = 2
Values can also be set using a dot notation for the path e.g.
[dict setInt:3 forPath:@"dictLevel1.dictLevel2.newInt"];
Which yields:
dict = {
    int = 0;
    dictLevel1 =     {
        int = 1;
        dictLevel2 =         {
            int = 2;
            newInt = 3;
        };
    };
}
If a nested dictionary doesn't exist or isn't mutable the dictionary is updated. In this example setting an array (myArray) to and undefined dictionary (dictLevel3) creates the dictionary:
NSArray* myArray = @[@"1", @"2"];
[dict setObject:myArray forPath:@"dictLevel1.dictLevel2.dictLevel3.a"];
Which yields:
dict = {
    int = 0;
    dictLevel1 =     {
        int = 1;
        dictLevel2 =         {
            int = 2;
            dictLevel3 =             {
                a = [ 1, 2 ];
            };
            newInt = 3;
        };
    };
}