Categories and +load

If you’re a Cocoa plugin writer, sanctioned or otherwise, you’ve probably thought about categories. About how you can magically add methods to existing classes…and if you’re careful, you can replace existing methods as well. With a few caveats: you can’t call the original method, and if someone else is doing the same thing, only one of you will win. Which makes it a bad idea, at best.

Well, today I was absentmindedly reading through GCC extensions to the C languages, and came across this tidbit:

The +load is a method that is not overridden by categories. If a class and a category of it both implement +load, both methods are invoked. This allows some additional initializations to be performed in a category.

!! Categories get their own +load methods? It’s just like every class getting its own +initialize! With this here, you can safely add functionality to existing methods using categories:

  1. Create a method with an unlikely prefix: -(id)ComBelkadan_valueForKey:(NSString *)key.
  2. Have that method call itself when it would be calling the original method.
  3. In +load, swap the implementations of the two methods (using something like JRSwizzle).

Now if someone else comes along and does the same thing, the methods will chain together, eventually calling the original implementation as intended. Has anyone been using this before or has no one known about it? (And, will the alternative compiler Clang/LLVM offer the same functionality?)

Remember, you can’t trust very much during +load. But you can do enough, here. (And because this is a category in a plugin we’re talking about, you can probably assume the rest of the application and frameworks have loaded anyway.)

There are some interesting things in the GCC language extensions. Even if you don’t end up using them, they’re fun to take a look at.