I saw a very good sample here:
Subclass UIButton to add a property
What is it? You can’t add object to a category. But now with this trick you can.
So what is it? How does it work?
Objective-c object already have some constant number of ivar pointers right?
Now you add another one? How did they figure that out?
A pretty ugly notation I must admit.
With the Associative References trick, you’re not actually adding any instance data to the UIButton object. Instead, you’re using a totally separate Cocoa facility to create a new dictionary mapping (or associating) existing UIButton objects with data that’s stored elsewhere in the heap.
You could do exactly the same thing without using Cocoa’s Associative References; it would just be even uglier and probably less efficient. It would go something like this, in Objective-C++. (I’m not even going to try to write it in Objective-C, because
CFMutableDictionaryandNSMutableDictionaryboth have the wrong behavior on a couple of levels, and I’m not going to write the whole thing from scratch. However, C++’sstd::mapcan’t be used with__weakreferences the way I want to use it, so I’m falling back on this inefficientstd::vectoralgorithm. For those unfamiliar with C++:std::vectoris roughly equivalent to anNSMutableArray, except that you get to choose whether it retains its contents.)The point is that the UIButton objects aren’t being changed; what’s changing is the contents of this additional dictionary. The property getter and setter simply know how to look things up in that dictionary so that it appears as if the UIButton has a new property.
See also: http://labs.vectorform.com/2011/07/objective-c-associated-objects/