iOS Programming Recipe 12: Saving Time With Literals

Assumptions

  • You have basic knowledge of Objective-C and Foundation.
  • You are familiar with NSArray and NSDictionary.
What Are Literals?

Literals in programming refer to constant values that can be directly written out in source code.


"dog food"      //C string literal  
@"dog food"     //Obj-C string literal  
17              //integer literal    
17.0f           //float literal

The listing above shows a few common examples of literals you probably use frequently.

So what’s the big deal?

Until recently, objective-C has had what some might call pathetic support for literals. Of course numbers and strings as shown above have been available, but container objects such as arrays and dictionaries? Well, in the not too distant past you would have had to write something like the following to initialize an array.


NSArray *brandsOfCatFood = [NSArray arrayWithObjects:@"Fancy Feast", @"Meow Mix", @"Whiskas", @"Pounce"];

That doesn’t seem too bad… but what about something even more complex.


NSArray *brandsOfCatFood = [NSArray arrayWithObjects:@"Fancy Feast", @"Meow Mix", @"Whiskas", @"Pounce"];
NSArray *brandsOfDogFood = [NSArray arrayWithObjects:@"Happidog", @"Friskies", @"Kibbles 'n Bits", @"Science Diet"];

NSDictionary *petFoodBrandsByAnimal = [NSDictionary dictionaryWithObjectsAndKeys:brandsOfCatFood, @"cat", brandsOfDogFood, @"dog", nil];

with literal syntax this becomes


NSDictionary *petFoodBrandsByAnimal = @{
                                            @"cat" : @[@"Fancy Feast", @"Meow Mix", @"Whiskas", @"Pounce"],
                                            @"dog" : @[@"Happidog", @"Friskies", @"Kibbles 'n Bits", @"Science Diet"]
                                        };

much better!

So let’s break that down a bit…

NSArray & NSDictionary Literals

Creating arrays and dictionaries.


NSArray *array = [NSArray arrayWithObjects: …, … ];

//using literal syntax
NSArray *array = @[ …, … ];

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:object, key, …, nil];

//using literal syntax
NSDictionary *dictionary = @{ key : value, … };

The syntax is not limited to creation, it can be used for accessing as well


id objectAtIndexTwo = [array objectAtIndex:2];

//becomes
id objectAtIndexTwo = array[2];

//with a mutable array you can use it to set objects
NSMutableArray *mutableArray = [NSMutableArray array];
mutableArray[0] = @"jackalope";

id objectForKey = [dictionary objectForKey:@"jackalope"];

//becomes
id objectForKey = dictionary[@"jackalope"];

//with a mutable dictionary
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionary];
mutableDictionary[@"key"] = @"value";
NSNumber Literal

Many times it becomes necessary to put  primitive types in a collection object such as an NSArray or NSDictionary.  The problem is you quickly find out that NSArray or NSDictionary only accept Objective-C objects which excludes primitives such as numbers!

The way to get around this is to box the primitive number with an NSNumber like so


NSInteger myLuckyNumber = 17;
NSNumber *myLuckyNumberObject = [NSNumber numberWithInteger:myLuckyNumber];

NSArray *luckyNumbers = [NSArray arrayWithObjects:myLuckyNumberObject];

More information on boxing and the efficiency of such madness

Seems kind of tedious right?

Well, literals to the rescue once again! All you have to do is prefix the primitive number with @ to box it with NSNumber.


NSArray *luckyNumbers = @[@myLuckyNumberObject];

So here you have it, literal syntax for NSString, NSArray, NSDictionary, and NSNumber
1

Closing Thoughts

I know we have used some of the literal notation in previous recipes without proper explanation… sorry about that! However, you now know what it is and exactly how to use it when you see it in the future.

This is just one example of the many time saving advancements Objective-C, Clang, and LLVM have made recently. We will try to cover some of the others such as ARC, automatic property synthesis, etc. in future recipes.

If you are really excited about literals and want to learn more about how they work under the hood check out Mike Ash. More information can also be found at Clang documentation, they have some great examples!

As always, please feel free to comment, ask questions, or rant (if that’s your thing).

Comments

  1. Would be this also valid?
    NSArray *luckyNumbers = @[@17, @25, @33];

    • Sure,

      NSArray *luckyNumbers = @[@17, @25, @33];

      would be an NSArray filled with NSNumber objects. It’s worth noting, when using literal syntax as shown above you don’t nil terminate the arguments as you do when using arrayWithObjects:.

Speak Your Mind

*

css.php
Privacy Policy