Nov 3, 2010

Catgories in Objective-C

Today I want to give a short example on how to use Categories in Objective-C to extend an existing class.
Let's say that you want to access safely to an array containing 'n' objects, but you don't want every time you access it to check if the index is contained into the array count.

A possible solution is to use a Category to extend the NSArray class.

Create a new project and add to it a new .h and .m files. Let call them NSArray+SafeAccess.h and NSArray+SafeAccess.m.
Inside the NSArray+SafeAccess.h put the declaration of the new Category:

@interface NSArray (SafeAccess) 

- (id)objectSafeAtIndex:(NSUInteger)index;

@end

Then in the NSArray+SafeAccess.m file write the implementation of the new method that will extend the NSArray with the safe access without obtaining a crash for out of bounds access:

@implementation NSArray (SafeAccess)

- (id)objectSafeAtIndex:(NSUInteger)index {
    return (index >= [self count]) ? nil : [self objectAtIndex:index];
}

@end

Later on in your code just import the NSArray+SafeAccess.h and you can use the new safe access method.
Try these lines of code:

#import "NSArray+SafeAccess.h"

...

NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:@"First"];
[arr addObject:@"Second"];
[arr addObject:@"Third"];

id obj = [arr objectSafeAtIndex:3];
assert(obj == nil);
obj = [arr objectSafeAtIndex:2];
assert(obj == @"Third");
[arr release];

Hope you enjoy with this simple example.
Comments and suggestions are welcome :)