Moving to new Objective-C literals

July 30, 2012

Last week, I moved one of my projects over to use the new Objective-C literals for NSNumber, NSArray and NSDictionary as well as the new syntax for boxing expressions into NSNumber and NSString objects.  Here are a few comments on how it went.

In a nutshell, the new language features allow code like [NSNumber numberWithInteger:7] to be replaced by a more compact syntax like @7.  The LLVM site has a full description of the new syntax and usage.

Refactoring in Xcode

I ran the ‘Convert To Modern Objective-C Syntax’ refactoring tool in Xcode 4.4 to do the conversion.  There is no option to choose which modern syntax features you wish to adopt before the conversion begins, but in Xcode 4.4, you can choose diff by diff which changes you wish to keep.  Xcode seems to think my Objective-C syntax is already modern enough in other respects, since the only changes the refactoring made was to move to Obj-C literals.

Even if you want to introduce the new literals into your code manually, you might find it interesting to run the refactoring tool just to browse through its proposed changes.  You can cancel the changes rather than apply them, but just by reviewing the proposed diffs, you might see use cases for Obj-C literals that may not have occurred to you.

There were more places than I was expecting where my code creates NSNumber instances from integer expressions and enums.  Also, before running the refactoring tool, it had not occurred to me how often the expression being boxed would just be a single variable holding a scalar value.

So there were numerous places where the updated code did something similar to the following:

NSInteger myValue = 0;
// Do some stuff that changes myValue
[myArray addObject:@(myValue)];

Before doing the conversion on my own code, I definitely underappreciated the power and usefulness of boxed expressions.

Overall, I found the refactoring in Xcode 4.4. to be easy and straightforward.  The Xcode project I converted was a medium-sized Objective-C project using the iOS 5.1 SDK.

A crashing issue to watch out for

There is a potential crashing issue that I ran into that you should be aware of.  In one spot, the code was relying on a nil value terminating the list of arguments to create an array.  So something like:

-useRequiredValue:(id)requiredObj optionalValue:(id)optionalObj {
   NSArray *array = 
         [NSArray arrayWithObjects:requiredObj, optionalObj, nil];
   // Do something useful with array
}

The method +arrayWithObjects: stops processing arguments when it hits the first nil argument.  The code above relies on that fact to create a one-object array when optionalObj is nil, and a two-object array when optionalObj exists.

The conversion changed the array creation to:

NSArray *array = @[requiredObj, optionalObj];

With array literals, relying on a terminating nil does not work.  Behind the scenes, a literal NSArray is created with +arrayWithObjects:count: which requires non-nil values.  So, after converting to Obj-C literals, an exception was thrown whenever the optional argument was nil.

A similar issue arises with dictionaries if you are relying on early nil-termination with +dictionaryWithObjectsAndKeys: and then move to use an NSDictionary literal.

Note that this issue is not flagged by the refactoring tool or the static analyzer, so it is something to watch out for when converting to use Objective-C literals.

To address the issue, the options are either to revert to the previous code or change the code to something else.

I changed the code to something like this:

NSArray *array =
    (optionalObj != nil) ? @[requiredObj, optionalObj] : @[requiredObj];

I decided to stop using the ‘early nil’ approach for a few reasons.  The first is that I know I will be tempted to change that line of code to use a literal array every time I look at it, which will reintroduce the crash.  I could guard against that by adding an emphatic comment explaining the situation, to prevent myself from changing that line of code.  So, everytime I look at the code, I’ll be tempted to convert the line of code, and then have to read about why I can’t convert that line of code.

It seemed more maintainable to move to a different way of doing the same thing.  In addition, the new code is less tricky/clever than the old code and more explicit about what the result will be; no comment is needed.  I am a big fan of well-commented code, but I’m also a fan of code that is obvious enough that the code can clearly speak for itself.

Readability

In most cases, the new literal syntax leads to code that is both more compact and more readable.  In the above example, the new code is not much more compact than the original code, but, the intent is clearer, which I find more readable.  With numbers, @3.6 is more readable and compact than [NSNumber numberWithFloat:3.6].  For arrays and dictionaries, I find that my eyes are not yet parsing literal array and dictionary creation as smoothly as more familiar Objective-C code, but I suspect that will change as I use and see the new constructs more often.

Boxed expressions may cause readability to suffer to some degree.  When you encounter something like @(someVariable), it is ambiguous whether you are creating a number or string.  You need to know the type of the expression to know for certain.  In practice, descriptive variable names should make this less of an issue.

I find the code becomes less readable as the boxed expression inside the parenthesis becomes more complex and when Objective-C literals and boxed expressions are combined and nested.  We are moving from code that had giant billboards of [NSString stringWith…  or [NSNumber numberWith… proclaiming just what is being creating, to code which is definitely more compact, but may also be more difficult to read.  For example:

@{ValueAverage : @((self.currentValue - [self.relatedObject
    currentValue]) / 2), BoundaryValues : @[@(self.maxValue), @(self.minValue)]}

Even after such a short time using the new syntax, I find that on balance, the literals and boxed expressions make for more readable and compact code, with a few cases where readability seems to suffer a bit.  It is also early in the game, in terms of using the new syntax on a day to day basis.  My opinion will continue to evolve as I use the new constructs more.

Backward binary compatibility and a little BOOL wrinkle

The new Objective-C literal functionality is handled in the compiler, so you must be using a recent version of the LLVM compiler to use this syntax.  Since the compiler generates code that uses existing object creation methods, the code you write and compile can run on previous versions of OS X or iOS.

So, even if you are targeting releases of your app on OS versions earlier than OS X 10.8, or iOS 6, you can use the new literals along with the new version of the tools.

I did encounter one wrinkle with BOOL literals.  To enable the compiler to properly deal with @YES and @NO to represent NSNumber BOOL values, two new language keywords were added to the Objective-C headers.

The iOS 5.1 SDK does not include these new keywords.  So, if you are using Xcode 4.4 and the iOS 5.1 SDK, you need to ‘box’ the BOOL values as expressions to compile: @(YES) and @(NO).

The Mountain Lion 10.8 SDK does have the new keywords as will SDKs moving forward, so this is just a minor transitional oddity.

Conclusion

Overall, I think the new Objective-C literals and boxed expressions are an excellent addition to the language.  I found converting to the new syntax using Xcode 4.4 refactoring to be a smooth process.  The only real bump I hit was in code where I was relying on early nil termination of arguments when creating an array.  The other wrinkle I encountered was the need to box BOOL values using Xcode 4.4. and the iOS 5.1 SDK.   I’m looking forward to using these new language features moving forward.


Categories: Mac, Software Development, iOS

Tags: Compiler, LLVM, Low Level Virtual Machine, Mac, OS X, Objective-C, Xcode, iOS