Introduction to Objective-C for Programmers, part I

Introduction to Objective-C for Programmers, part I

Introduction to Objective-C for Programmers contains the following parts already:

 

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.

[NSNumber numberWithInt:42]

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 *fortyTwo = @42;        //initialize integral values

NSNumber *piFloat = @3.141592654F; //initialize floating point number object

You can actually initialize number literals in two ways:

NSNumber *value = @42;

NSNumber *otherValue = @(42);

They compile to the same assembly and produce the same result. There is a literal syntax for initializing Booleans too:

NSNumber *noNumber = @NO;

where before it would be:

[NSNumber numberWithBool:YES]

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:

NSString *str = @”Hello World!;

That’s all nice and usefull but with literals you can initialize arrays and dictionaries too, e.g.:

NSArray *array = @[ @"One", @”Two”, @”Three” ];

Or dictionary:

NSDictionary *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

NSMutableArray *array = ...;
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:

NSMutableArray *objects = [@[] mutableCopy];
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:

NSArray *array = [NSArray arrayWithObjects:@"foo", @"bar", nil];

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 *myString1 = @"foo";
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:

if ([a isEqualToNumber:b]) // if a == b

and for comparison:

if ([a compare:b] == NSOrderedSame) // if (a == b)
if ([a compare:b] == NSOrderedAscending) // if (a &lt; b) if ([a compare:b] == NSOrderedDescending) // if (a &gt; b)
if ([a compare:b] != NSOrderedSame) // if (a != b)
if ([a compare:b] != NSOrderedAscending) // if (a &gt;= b)
if ([a compare:b] != NSOrderedSescending) // if (a &lt;= 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:

Leave a Reply