Objective-C Literals

Xcode 4.4 ships with a new version of LLVM that supports a host of new syntactic sugar around collections. You used to have to write this:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];

Now you can write this:

NSDictionary *dict = @{ @"key1": @"value1", @"key2": @"value2" };

There’s a similar syntax for arrays. There’s also an easier way of subscripting. This is the old way:

id obj = [dict objectForKey:@"key1"];

This is the new way:

id obj = dict[@"key1"];

This all sounds wonderful in theory. Less typing! However, in practice:

  • Apple state in the release notes for Xcode 4.4 that this new syntax only works in OSX, but I’ve successfully used array, number and dictionary literals in an iOS app.

  • Attempts at subscripting arrays or dictionaries in iOS fail with a “bad receiver type” compiler error.

  • Subscripts work in OSX when compiled for “running”, but fail with the same compiler error when compiled for “archiving”.

As none of this seems to be documented anywhere (except on the LLVM website, which of course makes no mention of OSX or iOS and has no information on which bits of the syntax are available on which platform), I’m going to assume that subscripting is, at least for the moment, broken and unusable.