Coding standards: New Objective-C syntax that will make your code beautiful

Around the time that iOS 6.0 was introduced, Apple also submitted some “literal syntax” improvements to the LLVM project. These improvements include easy-to-read-and-write code improvements that are, in my opinion, worth getting used to.

Here are some examples of what I’m talking about:


Up until now, every time you wanted to create an array with predefined objects, you’d have to define it as something similar to:

NSArray *foodArr = [NSArray arrayWithObjects:@"hamburger",@"steak",@"salad"];

But now, thanks to the NSArray literals, you can simply do:

NSArray *foodArr = @[@"hamburger",@"steak",@"salad"];


Using literals with NSDictionary makes the awful:

NSDictionary *petsDict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"fido",@"rex",@"simba", nil] forKeys:[NSArray arrayWithObjects:@"dog",@"dino",@"lion", nil]];

available with a simple and understandable:

NSDictionary *petsDict =
@{  @"dog":@"fido",
    @"lion":@"simba" };


NSNumber literals make it easy to instantly create NSNumber instances with various primitive data types such as:

NSNumber *theIntFive = @5
NSNumber *aBooleanYes = @YES
NSNumber *floatPi = @3.14f

Aren’t these nicer than the [NSNumber numberWith…] convention?


I think that once these literal standards become something you’re accustomed to, your code will look better and your collaborators will become less eager to hunt you down and hit you with heavy office supplies for writing unreadable code. Enjoy!


Posted on December 8, 2012, in Coding standards. Bookmark the permalink. Leave a comment.

Say something...

Fill in your details below or click an icon to log in: Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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


Connecting to %s

%d bloggers like this: