category與associative作為objective c的擴展機制的兩個特性,category即類型,可以通過它來擴展方法;associative,可以通過它來擴展屬性;在iOS開發中,可能category比較常見,相對的associative,就用的比較少,要用它必須使用的頭文件,然後就
category與associative作為objective-c的擴展機制的兩個特性,category即類型,可以通過它來擴展方法;associative,可以通過它來擴展屬性;在iOS開發中,可能category比較常見,相對的associative,就用的比較少,要用它必須使用<objc/runtime.h>的頭文件,然後就可以自由使用objc_getAssociatedObject以及objc_setAssociatedObject,我們來看下這兩個方法:
/**
* 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.”
*
* @see objc_setAssociatedObject
* @see objc_removeAssociatedObjects
*/
OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);
/**
* 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);
另外還有一個方法:
/**
* Removes all associations for a given object.
*
* @param object An object that maintains associated objects.
*
* @note The main purpose of this function is to make it easy to return an object
* to a "pristine state”. You should not use this function for general removal of
* associations from objects, since it also removes associations that other clients
* may have added to the object. Typically you should use \c objc_setAssociatedObject
* with a nil value to clear an association.
*
* @see objc_setAssociatedObject
* @see objc_getAssociatedObject
*/
OBJC_EXPORT void objc_removeAssociatedObjects(id object)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);
objc_getAssociatedObject、objc_setAssociatedObject、objc_removeAssociatedObjects都是Obj-c中的外聯方法,object 參數作為待擴展的對象實例,key作為該對象實例的屬性的鍵,而value就是對象實例的屬性的值,policy作為關聯的策略,它的枚舉包括:
enum {
OBJC_ASSOCIATION_ASSIGN = 0,
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
OBJC_ASSOCIATION_RETAIN = 01401,
OBJC_ASSOCIATION_COPY = 01403
};
另外,objc_removeAssociatedObjects可以刪除指定對象實例的所有擴展屬性。
可以用它來綁定數據到控制項上,並可以自由讀取。