Friday, June 1, 2012

Adding Properties to Any Object via Associated Objects

Preamble (Ramble)

I've been thinking about this for a long time, but until I learned about objc_setAssociatedObject and objc_getAssociatedObject I was lost. Now I am found! (thanks to Tommy at SO and his comments here.) Via categories, I can now add any number of new properties to a class I don't control. Like UIView (as in this example). The category: UIView+ExtraVariables.h UIView+ExtraVariables.m Voila! Now you can refer to a view.secondDescription in any class that imports UIView+ExtraVariables.


What's the use-case for this? One simple example is a UIView that has a firstFrame property. You would set it on a viewDidLoad and return to it whenever you wish. You could even add a convenience method (setFrameToFirstFrame, for instance) to do the work for you. The point is that now you get categories with properties in them: true encapsulation.


So this is really cool. Let's encapsulate it a bit, just like grandma taught you: NSObject+AssociatedObjectSupport.h NSObject+AssociatedObjectSupport.m So your new categories would then:
  1. Define properties using @property as always
  2. Import NSObject+AssociatedObjectSupport.h in the category's .m file
  3. Define a key like static char key; in the category's .m file
  4. Define setters for each property, using setAssociatedObject to store
  5. Define getters for each property, using associatedObject to retrieve
Note: the associated property gets dealloc'ed when the instance gets dealloced. So it's all 100% consistent with normal coding.

No comments: