Introduction to Objective-C for Programmers, part I
Introduction to Objective-C for Programmers contains the following parts already:
- Part I – literals
- Part II – class cluster pattern, categories, description method
- Part III – method swizzling
- Part IV – error model, delegates
- Part V – blocks
If you are interested in iOS development and you still angry that you cannot grasp Objective-C easily like you do with other languages here is the simple and short quite for you. I won’t describe the very basics here like message passing, inheritance etc, that except the weird syntax is very similar to what you know from other programming languages.
I’ll try to describe some peculiarities of Objective-C syntax and common practices which I personally found new/strange/amazing while learning Objective-C as another language. This list is created for people who are just starting with Objective-C but are experienced programmers in other languages and created already one or two simple Objective-C applications.
Literal syntax of arrays, dictionaries, strings etc.
Number, String and Container Type Literals
First things you will look for when working with Objective-C is how to simplify objects creation as it looks quite cumbersome, e.g.
that’s lot of typing for such a simple object initialization. It turns out that there is other way to initialize common objects in Objective-C and much simpler, consider the following examples:
NSNumber *piFloat = @3.141592654F; //initialize floating point number object
You can actually initialize number literals in two ways:
NSNumber *otherValue = @(42);
They compile to the same assembly and produce the same result. There is a literal syntax for initializing Booleans too:
where before it would be:
If you typed at least a ‘Hello World’ type of program in Objective-C chances are high that you already used a string literal syntax:
That’s all nice and usefull but with literals you can initialize arrays and dictionaries too, e.g.:
Or dictionary:
@"name" : NSUserName(),
@"date" : [NSDate date],
@"processInfo" : [NSProcessInfo processInfo]
};
Subscripting
With literals added to the language there is a possibility to use subscripting with container type objects like the following
NSUInteger idx = ...;
id newObject = ...;
id oldObject = array[idx];
array[idx] = newObject; // replace oldObject with newObject
NSMutableDictionary *dictionary = ...;
NSString *key = ...;
oldObject = dictionary[key];
dictionary[key] = newObject; // replace oldObject with newObject
Tips And Tricks
When combining the container literals and subscripting we can come up with different ways of eg. Inserting an object into a mutable container:
NSObject *someObject = [NSObject new];
objects[objects.count] = object;
Above code mimics `addObject:` functionality using literals.
You can convert old style object creation with the ‘new’ literal way using xcode refactoring capabilities, for example consider the following snippet:
Higlight it in Xcode, go to ‘Edit’ menu, then ‘Refactor’ -> ‘Convert to Modern Objective-C Syntax..’
There is even more stuff you can do with literals like boxed expressions, enumerations, c style strings, I won’t touch that here as I haven’t seen them wildly used (at least yet).
Caveats
In addition there are some caveats which you should be aware of when using the Objective-C literals
“Objects created using the literal or boxed expression syntax are not guaranteed to be unique by the runtime, but nor are they guaranteed to be newly-allocated.”
In other words you should not use ‘==, =<, =>, >, <’ when checking equality or comparing objects created with literal syntax.
Example:
NSString *myString2 = @"foo";
NSString *myString3 = [[NSString alloc] initWithString:@"foo"];
NSLog(@"%d", (myString2 == myString3)) //0
NSLog(@"%d", (myString1 == myString2)); //1
NSLog(@"%d", [myString1 isEqualToString:myString2]); //1
NSLog(@"%d", [myString1 isEqualToString:myString3]); //1
Some examples of proper NSNumber comparison for equality checks:
and for comparison:
if ([a compare:b] == NSOrderedAscending) // if (a < b) if ([a compare:b] == NSOrderedDescending) // if (a > b)
if ([a compare:b] != NSOrderedSame) // if (a != b)
if ([a compare:b] != NSOrderedAscending) // if (a >= b)
if ([a compare:b] != NSOrderedSescending) // if (a <= b)
You can read more about literal syntax straight from the docs on Clang documentation at http://clang.llvm.org/docs/ObjectiveCLiterals.html
Introduction to Objective-C for Programmers contains the following parts already:
- Part I – literals
- Part II – class cluster pattern, categories, description method
- Part III – method swizzling
- Part IV – error model, delegates
- Part V – blocks