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.
Now you simply add the implementation, it’s that simple.
Happy coding.