So iOS 6 has been around for quiet some time now and so has the LLVM 4 compiler. Along with this Apple has made some subtle changes to ObjectiveC. They may seem trivial but trust me, they’re going to save a lot of time.
Apple has made changes to the way we create and use an NSArray, NSDictionary and NSNumbers.
The syntax has been made more NSString like and removes the overhead of alloc and init in most cases.
To create a NSNumber object, we no more have to use the following syntax:
NSNumber *anInteger = [NSNumber numberWithInt:89];
but instead, you can simply do:
NSNumber *anInteger = @89;
It is important to note that doing @”89″ would make it an NSString literal whereas @89 makes it a NSNumber literal.
You could also use :
NSNumber *floatValue = @3.14F; //Declaring a float
NSNumber *doubleValue = @3.14; //Declaring a double
NSNumber *unsignedInt = @89U; //Declaring an unsigned int
NSNumber *booleanValue = @YES; //Declaring a boolean
Prior to LLVM 4, arrays were created using syntax similar to :
NSArray *arrayOfMixedObjects = [NSArray arrayWithObjects:obj1, obj2,.....,nil]; // A single NSArray instance can hold objects of different types
But now with LLVM 4, we simply use :
NSArray *arrayOfMixedObjects = @[obj1, obj2, obj3]; // No need for a nil separated list here
You could also create an array of NSNumbers on the fly :
NSArray *arrayWithNumbers = @[@2, @4, @6];
Or a mixed array like :
NSArray *mixedArray = @[@"Hello", @"World", @1, @3.14F, @YES];
Now how do we access the elements within this array ? There’s a simpler way thanks to LLVM 4. Here’s how :
id *firstObj = mixedArray;
id *secondObj = mixedArray; // and so on....
This is very similar to the way array indices are accessed in languages like C and Java using subscripts, and there is no need for :
Well, LLVM 4 has changed the way create and access dictionaries as well. The new way to do this is :
NSDictionary *dictionary = @[@"key1":@"value1", @"key2":@"value2", @"key3":@"value3"];
Again, no need for “nil” termination.
And we use subscripts again to access values. Here’s how :
id *firstValue = dictionary[@"key1"];
id *secondValue = dictionary[@"key2"];// And so on ...
One very important note to remember is that, arrays and dictionaries created this way will be immutable only. To create immutable versions, you will have to use the traditional way to do so.
How do we check if these new LLVM 4 features are available ?
Well, the answer is simple, use the
// For Arrays
// do it the LLVM 4 way
// do it the old way
// For checking if Dictionary literals are available :
// do your thing
// For Dictionary/Array subscripts
// do your thing
As you can see, LLVM 4 is going to make our life with Arrays, Numbers and Dictionaries even more easier !