Day 7: In a state of disappointment (and some Cocoa)
365Cocoa.tumblr.com is in mourning today. Why? My severe disappointment about the delayed iPad launch outside US and the continuing uncertainty as to when the App store will open for native iPad apps. But there’s no way I can get around writing something today so even though my thoughts are elsewhere, here’s today’s entry:
Categories are one of my favorite language features in Objective-C and I use them a lot. Apart from the occasional category on Apple’s classes I use them a lot on my own. By the way, I recently came by a tweet from someone claiming that Categories break encapsulation. Can anyone explain me why this is apart from the fact that it, like anything else, can be abused?
I find categories to be very useful in helping me with sharing code between projects. An example is a class that is shared between an iPhone and a Mac version of an app. The Mac/iPhone specific stuff can be put in categories where the base class provides hooks that can be used by the categories instead of littering your file with preprocessor directives.
Let’s say you don’t use KVO on the iPhone, but do on the Mac. For example in the -init method one could write the following without the category actually being present:
SEL KVOHook = @selector(keyValueCodingSetupHook)
if ([self respondsToSelector:KVOHook])
[self performSelector:KVOHook];
You could also declare an anonymous category on the class or use subclasses to provide this functionality, I prefer categories myself. Also in this way, I clearly see the hook that will be called instead of me completely forgetting that I subclassed this class and did something special there.