objc_setAssociatedObject 是<objc/runtime.h> 下的函數(shù)鸽粉,所以需要添加頭文件:
import <objc/runtime.h>
函數(shù)的具體定義是:
/**
* 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)
方法的主要作用是:
讓一個對象和另一個對象關(guān)聯(lián)起來,即一個對象保持對另一個對象的引用抓艳,并可以獲取這個對象触机。關(guān)鍵字是一個void類型的指針。每個關(guān)鍵字必須是唯一的玷或,通常都是會采用靜態(tài)變量來作為關(guān)鍵字儡首。
參數(shù)解析:
id object :關(guān)聯(lián)的源對象
const void *key:關(guān)聯(lián)的key
id value:關(guān)聯(lián)對象,通過將此個值置成nil來清除關(guān)聯(lián)偏友。
objc_AssociationPolicy policy:關(guān)聯(lián)的策略
關(guān)鍵策略是一個enum值
OBJC_ASSOCIATION_ASSIGN = 0, <指定一個弱引用關(guān)聯(lián)的對象>
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,<指定一個強引用關(guān)聯(lián)的對象>
OBJC_ASSOCIATION_COPY_NONATOMIC = 3, <指定相關(guān)的對象復(fù)制>
OBJC_ASSOCIATION_RETAIN = 01401, <指定強參考>
OBJC_ASSOCIATION_COPY = 01403 <指定相關(guān)的對象復(fù)制>
當(dāng)需要獲取關(guān)聯(lián)對象的時候:
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)
OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0);
例子:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
int main(int argc, char *argv[]) {
@autoreleasepool {
static char overviewKey;
NSArray *array = [[NSArray alloc] initWithObjects:@"one", @"two", nil];
NSString * overview = [[NSString alloc] initWithFormat:@"%@",@"First three numbers"];
objc_setAssociatedObject(array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);
NSString *associatedObject = (NSString *)objc_getAssociatedObject(array, &overviewKey);
NSLog(@"associatedObject:%@", associatedObject);
objc_setAssociatedObject(array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN);
}
}
輸出的結(jié)果:
2017-09-27 18:40:45.070 Untitled 3[28934:2258451] associatedObject:First three numbers