Sunday, September 2, 2007

Categories are cool

Perhaps not cool in the Samuel L Jackson sense, but categories are damn cool in the ‘holy cow I can extend something without replacing the class’ sense....if that is indeed a sense.

Class categories are a way of adding functionality to a an existing class where you don’t need additional instance variables.

If your new functionality needs instance variables, then subclassing is the go, but there is no need to subclass unless you're adding instance variables or override existing methods. Instead adding a class category will mean that you don’t have to worry about refactoring your existing code to use the new functionality. This is really handy where the original class is not your own.

Let’s have a look at a Cocoa Objective C example. NSXMLElement represents and XML Node and currently has a the following method.



The problem with this is that we have a lot of circumstances where we don’t want an array, just the first element with that name (if there is one). NSXMLElement doesn’t currently provide this functionality, so instead, each time we wanted the first element with that name we’d need to get an array using ‘elementsForName:’ then check to see that it has some elements, then get the first one. Rather than do all that, let’s just add a new method to NSXMLElement to give us this functionality without needing to do all this extra work each time we need it.

First, we start with a header:



Notice that there is no variables section. If you add the {} then it won’t compile.

Then we add the source:

Maybe not groundbreaking stuff, but handy none the less.