Objective C declaration shortcuts

With a recent update (okay, not quite so recent update) to Objective C, the following lexical shortcuts appear to have been added:

Create a dictionary using @{…}

The @{ … } shortcut has been added to create a new NSDictionary with a list of keys and values. The format appears to be:

@{ key : value , ... }

So, to create a new dictionary with three keys:

NSDictionary *d = @{ @"a": @"First",
                     @"b": @"Second",
                     @"c": @"Third" };

This creates a dictionary with three keys: @”a”, @”b” and @”c”, with the values @”First”, @”Second” and @”Third”, respectively.

Create an array using @[ … ]

The @[ … ] shortcut creates a new NSArray with a list of values. The format appears to be:

@[ value, value, ... }

So, to create a new array with three items:

NSArray *a = @[ @"a", @"b", @"c" ];

This creates an array with three items, @”a”, @”b” and @”c”.

Create an NSNumber wrapper around a numeric constant using @(…)

The @(…) appears to take a scalar and wrap it in an NSNumber object. Thus:

NSNumber *n = @( 5 );

creates a new NSNumber with the value 5.

You can combine each of these together in any way you wish. For example:

NSDictionary *d = @{ @(1): @[ @"A" ],
                     @(2): @[ @"Another", @"Thing" ],
                     @(3): @[ @"Tom", @"Dick", @"Harry" ] };

Far more convenient than the old way.

I’ve seen the first two documented elsewhere, but I don’t think I’ve seen the third one (boxing an NSNumber) mentioned anywhere, and I don’t quite remember where I saw it. Probably in the compiler release notes.

Also note that these can be used in-line with code and not just with constant objects. So, for example, you can use the NSNumber boxing mechanism to box an integer return value from a function:

NSNumber *count = @( [array count] );

This has been a public service announcement.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s