HHAssociatedObjects
May 19, 2010 10:20 AM
| Cocoa, Development, Mac
| Permalink
Mac OS X 10.6 introduced associated objects by the means of objc_getAssociatedObject and objc_setAssociatedObject. These provide a very convenient method for attaching object values to random objects. Associated objects can conveniently share the lifespan of the object they are associated with.
One situation where associated objects come in especially handy is when writing categories. Associated objets may be used be category methods to store state. It's the closest thing we got to adding instance variables.
The catch being that many projects still need to support Leopard. HHAssociatedObjects implements the concept of associated objects to support Leopard and Snow Leopard. Where available, the objc_getAssociatedObject and objc_setAssociatedObject methods are used. Elsewhere a NSMapTable is used to store associate objects.
HHAssociatedObjects are made available as a category on NSObject. I settled on the same API as Andy Matuschak. On Snow Leopard the implementation is actually the same as Andy's. HHAssociatedObjects adds a Leopard compatible implementation.
One situation where associated objects come in especially handy is when writing categories. Associated objets may be used be category methods to store state. It's the closest thing we got to adding instance variables.
The catch being that many projects still need to support Leopard. HHAssociatedObjects implements the concept of associated objects to support Leopard and Snow Leopard. Where available, the objc_getAssociatedObject and objc_setAssociatedObject methods are used. Elsewhere a NSMapTable is used to store associate objects.
HHAssociatedObjects are made available as a category on NSObject. I settled on the same API as Andy Matuschak. On Snow Leopard the implementation is actually the same as Andy's. HHAssociatedObjects adds a Leopard compatible implementation.
Comments