Adventures in Objective-C: Categories

Apple Developer

Every year Apple has been making Objective C and Xcode easier and easier to be picked up by developers like me – coming from a background in high-level OO languages (ActionScript, Java) with little to no experience in C – people for whom terms like “memory management” evoke images of creepy dark things crawling from under the shadows of our beds at night.  Still, Objective-C is basically an OO scaffolding to make C into an OO language, and as we have been learning through our development projects, there is plenty of history (or “baggage” as one of my CS engineer colleagues likes to say – he has the C background from back in the day that I don’t) as a result of C being a very old language.  The end result is, while we are able to jump in and crank out working applications, there seems to be always plenty to learn – there are lots of quirks and new twists that someone like me just isn’t used to.  The one I want to highlight today is Categories in Objective C.

Categories are the easiest way to modify existing classes in Objective C. And why not just extend the class like we would in any other OO language? Here’s why (from the apple docs):

Furthermore, it might not make sense to subclass the existing class, because you may want your drawing behavior available not only to the original NSString class but also any subclasses of that class, like NSMutableString. And, although NSString is available on both OS X and iOS, the drawing code would need to be different for each platform, so you’d need to use a different subclass on each platform.

Here’s the link to the full article in the Apple docs.

 

**Edit: comment from Luis Solano  over twitter:

@flexRonin nice. I’d strongly suggest to always prefix methods in categories with a three letter prefix to avoid collisions.

, , ,

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.