Episode #27

New Objective-C Syntax

13 minutes
Published on August 2, 2012
The latest version of the LLVM compiler supports some excellent new syntax additions to the Objective-C language. In this episode, I cover what the new syntax is, how to use it, and a few caveats to look out for.

Episode Links

The new syntax is supported in Xcode 4.4, and has no runtime requirements, meaning you can use this today if you're on the latest tools!

New Collection Literals

Creating an NSDictionary is much easier:

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
       [NSNumber numberWithBool:YES], @"backup",
       [NSNumber numberWithInt:7],    @"daysToKeepBackup,
       @"foo",                        @"flags", nil];

// becomes:
NSDictionary *options = @{ 
  @"backup": @YES,
  @"daysToKeepBackup": @7,
  @"flags", @"foo"
};

Arrays also got some love:

NSArray *items = [NSArray arrayWithObjects:@"item1", [NSNumber numberWithBool:YES], [NSNumber numberWith:12], nil];

// becomes:

NSArray *items = @[ @"item1", @YES, @12 ];

Subscripting

Subscripting is now supported if you're building for iOS 6 / 10.8. It looks like this:

id item = myArray[0];

id item2 = myDictionary[@"myKey"];

These are equivalent to objectAtIndex: and objectForKey: respectively.

Boxing Expressions

Sometimes you want to use an object literal for a BOOL or int, but the result needs to be calculated. To do this, you have to use parentheses:

NSNumber *total = @(28.90f - 1.89f);
NSNumber *disabled = @(!enabled);

C Strings

You can also easily convert a unicode C string into an NSString:

char * str = "I am a nil terminated C string";
NSString *myString = @(str);

Note that this only works if the string is in utf-8 encoding and is nil terminated.

Want more? Subscribers can view all 587 episodes. New episodes are released regularly.

Subscribe to get access →

Source Code

View on GitHub Download Source