objc_setAssociatedObject 是<objc/runtime.h> 下的函数,所以需要添加头文件:
import <objc/runtime.h>
函数的具体定义是:
/**
* 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)
方法的主要作用是:
让一个对象和另一个对象关联起来,即一个对象保持对另一个对象的引用,并可以获取这个对象。关键字是一个void类型的指针。每个关键字必须是唯一的,通常都是会采用静态变量来作为关键字。
参数解析:
id object :关联的源对象
const void *key:关联的key
id value:关联对象,通过将此个值置成nil来清除关联。
objc_AssociationPolicy 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_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);
}
}
输出的结果:
2017-09-27 18:40:45.070 Untitled 3[28934:2258451] associatedObject:First three numbers