Monday, July 6, 2009

A Single-Instance Case against Obj-C Categories

This will be brief.

In Obj-C, there's this very cool feature called a Category, that lets you add functionality to an existing class. Note that this is not the same as extending the class, which results in a newly minted "subclass". It lets you add functionality to existing classes, whether you originally defined them or not.

Now, I love Categories. I've done lots of cool, otherwise-complicated things with them in my iPhone code.

However, I ran into a serious bug that took away an evening for me because between iPhone OS 2.x and 3.0, one of my Categories (on NSMutableArray, to be exact), came into conflict with one of Apple's. In a nutshell, I added -(id)pop; to NSMutableArray+GameChanger.h, though this was a 'pop' function for a FIFO queue, whereas it seemed that Apple had implemented 'pop' for a traditional FILO stack. I only discovered this because there was a bug where the Navigation Bar views in my app went insane, and I sat down and read all of the documentation on how they function, only to realize they were using an array for a stack, which jogged my memory about my little 'pop' function.

At the very least, the compiler should have warned me that my 'pop' function conflicted with another category. Then again, there are a lot of strange ugly things about Obj-C & XCode that I wish Apple would work on (Obj-C 3.0, anyone)? That's another post.