Saturday, September 22, 2012

Dictionary Literals


Before Xcode 4.4 I didn't think I could write such strange things in Objective-C:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSMutableDictionary *test = [[NSMutableDictionary alloc]
                                     initWithDictionary@{ @"key 1" : @"value 1"@"key 2" : @"value 2"@"key 3" : @"value 3" }];
        NSLog(@"test dictionary: %@", test);
        
        NSLog(@"key 2 = %@", test[@"key 2"]);
        test[@"key 2"] = @"value 2 changed";
        NSLog(@"changed test dictionary: %@", test);
        
        NSUInteger idx = 3;
        test[[NSString stringWithFormat:@"key %lu", idx]] = @"Hello, world!";
        NSLog(@"changed test dictionary: %@", test);
    }
    return 0;
}

Even this terrible line:
        test[[NSString stringWithFormat:@"key %lu", idx]] = @"Hello, world!";

works just fine: 

2012-09-22 11:22:06.569 TestDictionary[18727:303] test dictionary: {
    "key 1" = "value 1";
    "key 2" = "value 2";
    "key 3" = "value 3";
}
2012-09-22 11:22:06.571 TestDictionary[18727:303] key 2 = value 2
2012-09-22 11:22:06.571 TestDictionary[18727:303] changed test dictionary: {
    "key 1" = "value 1";
    "key 2" = "value 2 changed";
    "key 3" = "value 3";
}
2012-09-22 11:22:06.572 TestDictionary[18727:303] changed test dictionary: {
    "key 1" = "value 1";
    "key 2" = "value 2 changed";
    "key 3" = "Hello, world!";
}

More about Objective-C Literals:


  Objective-C Literals