NSArray Literals In Objective-C

When running Xcode 4.4 (the latest download from the Mac App Store) I noticed the option for Apple LLVM Compiler 4.0:

One reason this is significant is that you can now define literals for a number of additional objects, similar to how you define string literals with the @ prefix. In this post I’ll show you how to use NSArrays literals. Let’s look at a few examples:

// Previous format to define empty array
NSArray *emptyArray = [NSArray array];
// Previous format to define single element array
NSArray *singleElementArray = [NSArray arrayWithObject:@"Error Message"];
// Previous format to define array of strings
NSArray *arrayOfStrings = [NSArray arrayWithObjects: @"First Name", @"Last Name", nil];

The new NSArray literal format follows:

// Literal format for empty array
NSArray *emptyArray = @[];
// Literal format for single element array
NSArray *singleElementArray = @[@"Error Message"];
// Literal format for array of strings
NSArray *arrayOfStrings = @[@"First Name", @"Last Name"];
// Literal format for array of objects
NSArray *arrayOfObjects = @[singleElementArray, arrayOfStrings, singleElementArray];

Notice there is no nil value required for the array of objects! Let’s take a look at why that is. If you write something like this:

NSArray *arrayOfStrings = @[@"First Name", @"Last Name"];

The compiler will now generate the following code:

id objects[] = { @"First Name", @"Last Name" };
NSUInteger count = sizeof(objects) / sizeof(id);
NSArray *arrayOfStrings = [NSArray arrayWithObjects:objects count:count];

And with is approach, if you enter nil for any argument, the compiler will generate an error. For example:

NSArray *arrayOfStrings = @[@"First Name", nil, @"Last Name"];

Will result in an error Collection element of type “void” is not an Objective-C object.

NSArray literals are a very welcome addition to Objective-C. Stay tuned – in upcoming posts, I’ll also show you how to work with NSDictionary and NSNumber literals.

    • This is a good idea if an object is needed that represents a null value. On the other hand, when null values are not needed, no longer needing to terminate a list of objects when creating an array is a nice addition to the language.

  1. HI sir

    Thank u for seeing opportunity this is using great fully ,

Comments are closed.