× {{alert.msg}} Never ask again
Receive New Tutorials
GET IT FREE

Introduction to Objective-C Literals for iOS Beginners

– {{showDate(postTime)}}

Brett Romero has been developing iOS apps for the last several years and has 8 apps in the iTunes app store.   As an experienced iOS developer, Brett believes it is important for those new to iPhone development to know about Object-C literals.

Although Swift may be easier to learn for beginners, many iOS developers who embrace Swift would still recommend learning Objective-C, as many frameworks have not made the transition yet. What is more, as Swift is based on Objective-C, knowing Objective-C will make learning Swift easier as well.

Objective-C literals are not a new thing, but many beginners to iOS development might have overlooked it, especially if they’ve decided to start out with learning Swift. If you’re one of those people, now’s the time to get a gist of what literals are about!


Objective-C literals are a more simple, shorthand method for working with some common Objective-C constructs. These include the following:

  • NSNumber
  • NSArray
  • NSDictionary

These newest literal additions were introduced with the Apple LLVM 4.0 compiler. and Xcode 4.4.

You have likely already used literals and just didn’t know it. NSString objects have supported this syntax for a long time. Here’s an example:

NSString *string = @"hello world";

What makes the above so special that we call it a literal? It’s basically use of the @ symbol to declare an object instance. All of the scaffolding code that normally creates the instance isn’t needed with literals. This can save you lots of time depending on how familiar you are with declaration code for the above object types.

Let’s look at a quick example to get a better idea of the benefits of literals. Below is the syntax for creating a new NSNumber using plain Objective-C:

NSNumber *firstNumber = [NSNumber numberWithInt:5];

The following is the same NSNumber using literals:

NSNumber *firstLiteral = @7;

Simpler and more straight forward right? With this syntax, there are fewer parameters to remember and in some cases none. The code is also more concise and easier to read.

Now with Swift (Apple’s newest programming language), this has become the general direction Apple is taking with software development, making iOS programming accessible to a larger audience of programmers.

Because literals are Objective-C, there isn’t anything special you need to do to use them.

Literals also work in the Swift programming language and are a nice complement to Swift’s simplified syntax.


NSNumber

To get a comparison, let’s see how to add two numbers using regular Objective-C syntax. To do this, we must first create two NSNumber objects that contain the values we want to add. Next, we add the two numbers using another NSNumber object. Finally, the resulting sum is stored in yet another NSNumber object.

NSNumber *firstNumber = [NSNumber numberWithInt:5];
NSNumber *secondNumber = [NSNumber numberWithInt:7];
NSNumber *sum = [NSNumber numberWithInt: [firstNumber intValue] + [secondNumber intValue]];

Now let’s try it with literals. In this case, we have one less NSNumber object to deal with. Notice we don’t need to explicitly reference an NSNumber to sum our two numbers. Additionally, the syntax involved is greatly simplified.

NSNumber *firstLiteral = @7;
NSNumber *secondLiteral = @10;
NSNumber *sumLiteral = @([firstNumber intValue] + [secondNumber intValue]);

Comparing the two examples, you can see that literals are far more readable.

Breaking down the literal syntax, the left hand side is still the same. On the left hand side, we declare pointers:

NSNumber *firstLiteral

It’s the right hand side of the assignment where all of the action is happening. The @ symbol now replaces NSNumber and it’s companion or scaffolding code such as brackets and the parameter numberWithInt. This extra code is also not needed on the third line, where the summation occurs.

Adding the @ symbol is all you need to declare an NSNumber using literals.


NSArray

We’re going to use our NSNumbers from the previous example in an array. Just to recap, arrays are two dimensional objects that allow us to hold a list of objects. Basically, arrays are indexed, meaning you sequentially add objects to them. When you want the objects at a particular index, you reference that index and the object is returned.

In Objective-C, arrays are declared as follows:

NSArray *array = [NSArray arrayWithObjects:firstLiteral, secondLiteral, nil];

This may not look so bad but there’s some code here that isn’t really providing us any benefit. For example, we need to add a nil parameter to tell the compiler this is the end of our array. But why can’t the compiler just imply this since our array is only two objects long? We also must use the parameter arrayWithObjects.

By comparison, declaring an array with literals is quite simple:

NSArray *arrayLiteral = @[firstLiteral, secondLiteral];

Once again, the left hand side of the assignment is the same. We must declare the object type that will hold a value. But on the right side, we get away with just adding our two objects. Besides the @ symbol, there isn’t any other non necessary code required. The literal declaration is very clean.

You might be seeing a common use with the @ symbol. Good catch! It is the @ symbol that tells us we’re using literals. While the right hand side of the assignment may not provide much indication of the type being created, you can always tell this from the object type used on the left side.


NSDictionary

Dictionaries are similar to arrays except you can access objects stored in them using a key value rather than just a number or index. This key can have more meaning. It also means the dictionary isn’t necessarily storing objects in some particular order, since order likely has less importance when using dictionaries.

In Objective-C, the NSDictionary type is used to declare a dictionary. The syntax is similar to array declarations in that we must use some parameter and terminate with a nil. For dictionaries, the parameter is dictionaryWithObjectsAndKeys.

The following is an example of declaring an NSDictionary:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"key1", firstLiteral, @"key2", secondLiteral, nil];

Don’t be confused by the @ symbol in the above example. That just helps Objective-C denote keys from values. When declaring a dictionary, the key is declared followed by a comma and then the corresponding value. It is always declared in the order key then value. To declare more key/value pairs within the dictionary, just separate them by a comma, similar to what we did with NSArrays.

Once again, literals simplify this entire declaration:

NSDictionary *dictionaryLiteral = @{@"key1": firstLiteral, @"key2": secondLiteral};

You can see the dictionaryWithObjectsAndKeys parameter is not needed nor is the nil terminator. Also, the separation of key/value pairs is a little easier to read since everything is no longer separated by commas. Each key and value are now separated by colons. But each successive key/value pair is separated by a comma. This makes it easier to determine where the next key/value starts and one ends.

Conclusion

Objective-C literals are a great additional to your developer toolbox. The syntax is easy to remember and read. This can also help any team members better understand your code, ultimately improving overall productivity.


Brett RomeroNeed Brett’s help? Book a 1-on-1 session!

View Brett’s Profile

or join us as an expert mentor!



Author
Brett Romero
Brett Romero
5.0
Software engineer and startup founder. I have experience in .NET/C#, HTML/CSS, iOS and Wordpress. I'm constantly expanding my skill set. I also have an MBA from Arizona State University.
Hire the Author

Questions about this tutorial?  Get Live 1:1 help from iOS experts!
Ahsan Zia
Ahsan Zia
5.0
Full stack software developer with 6 years of experience
I am a full stack software developer and a Master of Android development while also having expertise on Python, Spring boot, .NET core, Laravel and...
Hire this Expert
Humayun Shabbir
Humayun Shabbir
5.0
Expert Visual Basic, C# and JavaScript Developer | 3500+ sessions
Welcome to my profile on Codementor! I'm a dedicated full-time mentor with a track record of over 3500 sessions since 2015. My journey in...
Hire this Expert
comments powered by Disqus