我們知道,使用Category可以很方便地為現(xiàn)有的類增加方法,但卻無法直接增加實例變量。不過從Mac OS X v10.6開始,系統(tǒng)提供了Associative References,這個問題就很容易解決了。這種方法也就是所謂的關(guān)聯(lián)(association),我們可以在runtime期間動態(tài)地添加任意多的屬性,并且隨時讀取。所用到的兩個重要runtime API是:
* objc_setAssociatedObject 添加關(guān)系
**
* Sets an associated value for a given object using a given key and association policy.
*
* @param object The source object for the association.
* @param key The key for the association.
* @param value The value to associate with the key key for object. Pass nil to clear an existing association.
* @param policy The policy for the association. For possible values, see “Associative Object Behaviors.”
*
OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
* objc_getAssociatedObject 取值
* Returns the value associated with a given object for a given key.
*
* @param object The source object for the association.
* @param key The key for the association.
*
* @return The value associated with the key \e key for \e object.
*
* @see objc_setAssociatedObject
OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);