iPhone Development: Reading Objective-C Methods

When teaching Objective-C, I’m finding that some have trouble reading method signatures.  Reading Objective-C methods can be made easier if proper spacing and indenting is used.

This is what a method looks like in Objective-C:

- (ret-type) keyword:(arg-type)arg-name keyword:(arg-type)arg-name

It is much easier to read if it is typed as such:

- (ret-type) keyword:(arg-type)arg-name
             keyword:(arg-type)arg-name

In the above signature, the minus sign implies that the method is an instance method.  Class methods are prepended with a plus sign.

The first keyword can be thought of as the method name.  In concrete terms, a method would look like this:

- (void) insertObject:(id)anObject atIndex:(NSUInteger)index

This is much easier to grok, if it is pictured like this:

- (void) insertObject:(id)anObject
         atIndex:(NSUInteger)index

And it can be read as “insert an object of type id at an index”.  This is easier to read at the point where a method is called.

Array* array = [[Array alloc] init]];
[array inserObject:anObject
       atIndex:0];

The above can be read as “insert an object into array at index 0”.  Objective-C is designed to be a self-documenting language.  Interfaces are generally designed such that they can be read in real English.