iOS运行时之二:关联对象

来源:互联网 发布:淘宝主图图片尺寸 编辑:程序博客网 时间:2024/05/16 11:50

关联对象(Associated Object)是Objective-C的运行时的一大特性,允许在运行时添加类的属性。

其实关联对象只有三个方法:objc_setAssociatedObject, objc_getAssociatedObject, objc_removeAssociateObjects.

关联对象可以通过一个给定的key(const void * 类型)关联到给定的对象上去。

static char BOOLRevealing;objc_setAssociatedObject(self, &BOOLRevealing, [NSNumber numberWithBool:YES], OBJC_ASSOCIATION_RETAIN_NONATOMIC);

以上例子是把一个NSNumber 对象通过BOOLRevealing这个key和类对象关联起来,这里还有一个关联策略的参数:

enum {    OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object.                                             *   The association is not made atomically. */    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied.                                             *   The association is not made atomically. */    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.                                            *   The association is made atomically. */    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.                                            *   The association is made atomically. */};

通过key获取关联对象:

objc_getAssociatedObject(self, &BOOLRevealing)

虽然有删除对象的方法objc_removeAssociateObjects,一般不需要手动去删除,例如替换key对应的属性,系统会删除关联对象,再把新的关联对象关联起来。

用例:AFNetWorking 三方库将请求队列绑定到UIImageview的对象上

- (AFHTTPRequestOperation *)af_imageRequestOperation {    return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_imageRequestOperation));}- (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation {    objc_setAssociatedObject(self, @selector(af_imageRequestOperation), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}


0 0