Joris Kluivers

I like to build software.

New Objective-C Literal Syntax for NSArray, NSDictionary

Apple committed a new patch to the llvm project adding support for new Objective-C literalsyntax for NSArray, NSDictionary and NSNumber. These have previously been documented in the Mountain Lion Xcode release notes but that was still under NDA. Now that these features have been committed to llvm I guess we’re allowed to speak about it.

Add clang support for new Objective-C literal syntax for NSDictionary, NSArray,
NSNumber, and boolean literals. This includes both Sema and Codegen support.
Included is also support for new Objective-C container subscripting.

My apologies for the large patch. It was very difficult to break apart.
The patch introduces changes to the driver as well to cause clang to link
in additional runtime support when needed to support the new language features.

Docs are forthcoming to document the implementation and behavior of these features.

No official documentation is available yet outside the NDA, but examples can be derived from the LLVM unit tests.

NSNumber literals

1
2
3
4
5
6
7
8
NSNumber *n1 = @1000;  // [NSNumber numberWithInt:1000] 
NSNumber *n2 = @3.1415926; // [NSNumber numberWithDouble:3.1415926]
NSNumber *c = @'c'; // [NSNumber numberWithChar:'c']
NSNumber *b = @YES; // [NSNumber numberWithBool:YES]

// uses the usual suffixes for `unsigned` (`u`) and `float` (`f`)
NSNumber *f = @2.5f;
NSNumber *nu = @256u;

NSArray literals

1
2
3
4
// before
NSArray *words = [NSArray arrayWithObjects:@"list", @"of", @"words", nil];
// after (array with some strings and numbers)
NSArray *words = @[@"list", @"of", @"words", @123, @3.14];

Note that it’s not needed to include the ending nil sentinel anymore using the new syntax.

NSDictionary literals

1
2
3
4
5
6
NSDictionary *d = @{
  @"key": @"value",
  @"name": @"Joris",
  @"n": @1234,
  @3: @"string"
};

As with NSArray no need to include the nil sentinel here either.