Note: This post is part 3 of a series of posts I will do about the new book of Matt Galloway.
Prefer Literal Syntax over the Equivalent Methods
Literals have been around objective-c since a long time:
NSString *aString = @"Hello World";
With the latest versions of Clang, this sugar syntax has been extended to
NSDictionaries. Since we deal with this kind of objects every day, this new feature is well appreciated. In a nutshell this allow us to:
- Reduce the boilerplate
- Cleaner code
- Faster typing
NSNumbers, you can use literals in the following way:
As you can see, in this case, the amount of extra code is reduced in more than 75%.
You can also use literals in collections with subscripting. With
NSArray you can do the following:
- By Array subscripting:
And finally with a
[NSDictionary dictionaryWithObjectsAndKeys:@"object1",@"key1",@"object2",@"key2" nil];
myDictionary[@"key1"] = @"newObject1";=>
[dic setObject:@"newObject1" forKey:@"key1"];
And if you want a mutable object:
[@[@"1",@"2" ] mutableCopy];
Although with collections the end result seems the same, if an object is
nil, it won’t. While using the common operations adding a
nil wouldn’t crash anything, with literals it will:
[NSArray arrayWithObjects:@"object1",nil, @"object2", nil]=> It’s “ok”.
@[@"object1",nil, @"object2"]=> It will raise an exception.
In theory it would be better if the first option would crash, because it doesn’t make much sense to have a
nil in the middle of an array and work with it in that state. Most of the time, you would prefer that would crash, so you could see immediately where the problem is.
Literals are an awesome addition in a very verbose language like objective-c. Knowing how to use them and their caveats is a must have for every programmer.