Extending classes in Objective C using Categories

Yesterday I had to perform the simple task of shuffling an array in Objective C. There is unfortunately no built-in method to do this (which is a bit strange) which meant I really wanted a way to add a shuffle method to the NSArray class. In C# I would use an extension method to do this, in Ruby I would use Open Classes and in Objective C we can use Categories.

Categories allows us to add methods to existing classes, even when we don’t have the source. This is a very powerful way of extending classes without subclassing.

Creating a new category is very simple – just use the XCode ‘New File…’ option, select category and select the class you wish to extend. The file name that gets generated is a bit weird (in my case it was NSArray+Shuffle), but the rest is reasonably intuitive.

In the header file, simply specify the methods you wish to add.

@interface NSArray (Shuffle)

- (NSArray *)shuffle;

@end

Now you simply add the implementation, it’s that simple.

@implementation NSArray (Shuffle)

- (NSArray *)shuffle
{
    NSMutableArray *shuffled = [NSMutableArray array];
    NSMutableArray *copy = [NSMutableArray arrayWithArray:self];
    
    while ([copy count] > 0)
    {
        int index = arc4random() % [copy count];
        [shuffled addObject:[copy objectAtIndex:index]];
        [copy removeObjectAtIndex:index];
    }
    
    return shuffled;
}

@end

Happy coding.