Tuesday, October 9, 2012

Modern Objective C : Literals

With the Introduction of iOS6 and the new LLVM Compiler Version 4.0, Apple introduced a few very handy and powerful features to the Objective C Language.

Finally, we have literals for NSNumber, NSArray and NSDictionary as well as Object Subscripting for Objective C Objects.
Those additions to the language are backwards compatible to all iOS versions with the exception of the Object Subscripting which deploys back to iOS4.

The new Literals essentially mean we have to write less code, the code we produce is easier to read and we can make fewer errors.

New Literals for NSNumber

The Literals for NSNumber support only scalar (BOOL, Numeric and enumerated) values and C String Pointer Types meaning @INT_MIN will not work as it is defined as (-2147483647-1).

NSNumber *theLetterZ = @'Z'; // equivalent to [NSNumber numberWithChar:'Z']
NSNumber *fortyTwo = @42;    // equivalent to [NSNumber numberWithInt:42]
NSNumber *fortyTwoUnsigned = @42U; // equivalent to [NSNumber numberWithUnsignedInt:42U]
NSNumber *fortyTwoLong = @42L; // equivalent to [NSNumber numberWithLong:42L]
NSNumber *fortyTwoLongLong = @42LL; // equivalent to [NSNumber numberWithLongLong:42LL]
// floating point literals.
NSNumber *piFloat = @3.141592654F; // equivalent to [NSNumber numberWithFloat:3.141592654F]
NSNumber *piDouble = @3.1415926535; // equivalent to [NSNumber numberWithDouble:3.1415926535]
// BOOL literals.

NSNumber *yesNumber = @YES; // equivalent to [NSNumber numberWithBool:YES]
NSNumber *noNumber = @NO; // equivalent to [NSNumber numberWithBool:NO]
#ifdef __cplusplus
NSNumber *trueNumber = @true; // equivalent to [NSNumber numberWithBool:(BOOL)true]
NSNumber *falseNumber = @false; // equivalent to [NSNumber numberWithBool:(BOOL)false]

Literals for NSArray and NSDictionary

The new Literals for NSArray and NSDictionary are, unfortunately, only working for immutable types meaning NSMutableArray and NSMutableDictionary are not supported

Example NSArray
NSArray *array = @[ @"Hello", NSApp, [NSNumber numberWithInt:42] ];

Example NSDictionary
NSDictionary *dictionary = @{
 @"name" : NSUserName(),
 @"date" : [NSDate date],
 @"processInfo" : [NSProcessInfo processInfo]

Subscripting for NSArray

Subscripting of NSArray and NSDictionary are well known in Dynamic languages such as PHP or Python and will offer alternatives to objectAtIndex: for NSArray and objectforKey: for NSDictionary. 

NSUInteger idx = ...;
id value = object[idx];

id key = ...;
id value = object[key];

All examples are taken from http://clang.llvm.org

No comments:

Post a Comment