DevJuice: Better Objective-C associated objects
Until now, I've been doing this:
static const char nametag_key;
return objc_getAssociatedObject(self, (void *) &nametag_key);
Turns out there's a much easier and better way. That's because Apple's selector implementation uses a fixed address. That means you can declare a property, for example:
@property (nonatomic) NSString *nametag;
and then use that property's selector as the key:
return objc_getAssociatedObject(self, @selector(nametag));
It's way cleaner, requires no extra static variables, and according to Gwynne, "It's absolutely safe and rather cutely self-documenting in current runtimes -- and for the foreseeable near future, no question."
Could this eventually break? Gwynne tells me that Apple would probably have to implement a completely new ABI for that to happen.
iOS/OS X internals guru Gwynne Raskind tipped me off to a much better way of creating associated object keys. Until now, I've been...
Subscribe to Newsletter
Software Updatesmore updates
- Daily App: MyScript Calculator solves your hand-written math equations
- Findery app lets you discover the world around you using annotated notes and maps
- The Learnist app brings its crowd-sourced collection of information to your iPhone
- My cat Cinnamon reviews Friskies Cat Fishing 2
- Photo Grid Collage Maker is capable and free
- iExit gets new features and is now free