Theocacao
Leopard
Design Element
Comment on "Class Variables and Categories"
by Dave — Nov 29
Hey all,

Maybe I can clear some things up. This definitely wasn't intended as a general purpose technique, we only use it in a couple of places. We did feel that it was interesting as we hadn't seen it used before, and just wanted to give people something to think about, not to mention clarify a bit how +load works, as Apple's documentation is a little lax in that area.

In one particular case we are adding a category onto NSString that has a collection of methods for creating enumerators for word breaking strings in special ways. These methods all use some hand created NSCharacterSets that are reasonably expensive to build. We are expecting these methods to be called from multiple threads, and as we're parsing a lot of text, we want them to be fast.

Before I continue, quick digression: one could easily argue that we should have a word-breaker class that takes a NSString. I'm not going to argue that, and we may well change the design in the future. It was a case where it started as a simple category, that grew substantially, and now we've got a good pile of code that depends on it. End of digression.

So, we've got some static NSCharacterSets that we need to initialize inside of a category. We can't use +initialize in a category for the reasons explained in the article. We can't depend on +load, because according to Apple's docs, and the code we have no guarantee that NSCharacterSet is even going to be +load'ed when we are loaded. We want things to be thread safe, and want to avoid the call to @synchronized whenever possible, so we want to avoid the lazy initialization. The constructor attribute gave us exactly what we wanted in this special circumstance.

As far as it being rickety syntax, it's not something Apple is going to be taking away lightly, as it is built into gcc, unlike some pragmas that they had previously.

The example that you show is an example of lazy-initialization. I did mention that it works fine, except that it has the usual lazy-initialization caveats of being slow.
Back to "Class Variables and Categories"
Design Element

Copyright © Scott Stevenson 2004-2015