Objective-C Literals

A "literal" refers to any value which can be written out directly in source code. For example, "hello" is a character literal and 32 is a integer literal. In the past Objective-C hasn't had support for defining literals, but as of Xcode 4.5 this is supported. The new syntax is also backwards compatible with older versions of iOS. Let's look at some NSNumber Objects.

[objc]NSNumber *celcius = [NSNumber numberWithInt:21]; NSNumber *pi = [NSNumber numberWithDouble:3.14159265359];[/objc]

With literals the new syntax will be.

[objc]NSNumber *celcius = @21; NSNumber *pi = @3.14159265359;[/objc]

The syntax in Arrays is also much simpler, let's look at an example of some arrays

[objc]NSArray *randomNumbers = [NSArray arrayWithObjects: [NSNumber numberWithFloat:-273.15, [NSNumber numberWithInt:90210], nil];

NSArray *names = [NSArray arrayWithObjects: @"Alex Smith", @"John Williams", nil];[/objc]

With literals everything between @[ ] becomes an item in an NSArray. Also , there's no need for a terminating nil sentinel. So you can write

[objc]NSArray *randomNumbers = @[ @-273.15, @90210]; NSArray *names = @[ @"Alex Smith", @"John Williams"];[/objc]

Let's look at dictionaries, first the original syntax.

[objc]NSDictionary *nameDictionary = [NSDictionary dictionaryWithObjectandKeys: firstName, @"Alex", lastName, @"Smith", nil];[/objc]

Dictionaries will have a similar syntax, everything between @{ } becomes an key-object pair. Note that ther order has changed in value,key.

[objc][NSDictionary *nameDictionary = @{ @"Alex" : firstName, @"Smith" : lastName};[/objc]

The preceding literal syntax @[ ] and @{ } create immutable objects. To make mutable objexts you have to call mutableCopy.

[objc]NSArray *names = [@[ @"Alex Smith", @"John Williams"] mutableCopy];

NSDictionary *nameDictionary = [@{ @"Alex" : firstName, @"Smith" : lastName} mutableCopy];[/objc]

That's it, as you can see the new literal syntax is much cleaner and simpler.