Objective C Categories

Categories take a little getting used to.

Objective-C categories let you add your own functionality to existing classes. This can take classes in directions that seem decidedly strange.

For example, if you want to draw a string in UIKit, you ask the string to draw itself. Coming from a Windows / Java background this seems weird. Why would a string know how to draw itself into a graphics context? But, on the other hand, why wouldn’t it?

With Objective-C, any object can be taught how to draw itself. Or how to serialise itself. Or any other bit of functionality that a particular library wants to add.

It’s a bit of a disconnect at first, but once you know it’s happening it makes perfect sense, and the idea of extending basic types with your own categories seems perfectly reasonable. Need to add a way to hex-encode the binary data in an NSData object? Add it right to the NSData object using a category. This makes it easier to find than the equivalent in other languages, which is typically to add some utility functions somewhere.

One tip: If you’re adding categories in a static library, you will need to specify the “-all_load” flag to the linker. If you don’t do this, the categories won’t be visible to the calling application and things won’t go well for you. Normally the linker will discard things that it thinks aren’t being used, and it seems to get this wrong about categories, but -all_load forces the linker to keep the category methods.