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.

Published by Fuad Kamal

Principal & lead architect of Anaara, Fuad develops enterprise native iOS applications for companies such as First Data & major telecom companies. He also mentors iOS & Swift for Thinkful. If you've been to any major airport in the world recently you've stared at his work - those flight arrival/departure screens are part of the Flight Information Display System (FIDS), whose interface he developed back in the day in Flash 7. In his spare time he enjoys martial arts, cycling, and photography. On rare occasion he will write poetry and work on post production for films.

Leave a comment

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