Your New Friends: Obj-C Associated Objects
There are tons of goodies in Snow Leopard for developers, but one of my favorites is associated objects, which allow you to tack arbitrary key/value pairs onto any
Since there’s no documentation whatsoever, I thought I’d introduce you.
Here’s how you’d store a value with a strong reference:
#import <objc/runtime.h> objc_setAssociatedObject(obj, key, value, OBJC_ASSOCIATION_RETAIN);
And how you’d get it back:
id value = objc_getAssociatedObject(obj, key);
key can be any
void *; it doesn’t have to implement
objc/runtime.h for the other memory management flags.
If you’re defining a category on a class you didn’t make, associated objects give you a non-hideous way to essentially add instance variables. I use them in KVO+Blocks to store observer data on objects.
Associated objects also come in handy when you need to keep a value around for a little bit, but it’s just not important enough to muddy up your header. Maybe you’re firing off some dialog asynchronously, and you want to free it when the callback is fired. Associated objects save you from having to make an instance variable for that.
Here’s a nice Obj-C category wrapping the C API. Enjoy!
Update: Kevin Ballard points out that since the key is just a
void *, you can also do this kind of thing:
static char key; objc_setAssociatedObject(obj, &key, ...);
This is especially elegant when
key can be method-local—when lazily loading some resource, for instance.