#Defining your wrappers
I’m working on a new project that uses ARC, because, frankly, I suck at memory management (in Objective-C and in real life). Zeroing weak references (ZWRs) are my absolute favorite new feature, as I use weak references fairly often to reference the parent object in a tree. So, I was very disappointed to learn that ZWRs do not, in fact, work on Snow Leopard.
Luckily, the Mac community came through for me, and I found MAZeroingWeakRef. It gives me all of the benefits of ZWRs without the limitation of excluding Snow Leopard users from the fun. The only downside of using it is that it makes your variable declarations somewhat opaque. For example:
NSPotato *parentPotato;
becomes:
MAZeroingWeakRef *parentPotato; // This is an NSPotato.
Now, this is a minor issue, but I like my interfaces to be as readable as possible, so I decided to come up with a way to remedy this. This is what I came up with:
#define weak(className) MAZeroingWeakRef
It’s just your average preprocessor macro, with a parameter that isn’t used in the definition to give you a place to put the actual class name. I just dropped that into my prefix (.pch) file, along with the #import statement for MAZeroingWeakRef.h, and now I can write:
weak(NSPotato) *parentPotato;
and my interfaces can live up to my own ridiculous standards again! The one thing you do have to remember is to import MAZeroingWeakRef.h wherever you use this.
The best part of this is that it will work for any wrapper style object, just swap out the relevant class and macro names in the #define, and away you go! So, say I had a wrapper for NSPotato objects called NSVegetable:
#define vegetable(className) NSVegetable
It’s that easy! Enjoy.
(Disclaimer: I haven’t tested this outside of Xcode 4.2, not sure if all versions of the preprocessor will take kindly to having an unused parameter in the macro. If you have issues, please let me know here or on Twitter, @SphereCat1.)