OC对象关联~objc_setAssociatedObject/objc_getAssociatedObject

首先引入<objc/runtime.h>的头文件


objc_setAssociatedObject  将一个对象与另一个对象相关联

objc_getAssociatedObject  取得关联的值 



#import <objc/runtime.h>


static char * const associativekey = "associativekey";


- (IBAction) buildAssociative
{
    objc_setAssociatedObject(obj_one, &associativekey, obj_two, OBJC_ASSOCIATION_RETAIN);
}

- (IBAction) getAssociativeValue
{
    id associativeObj = objc_getAssociatedObject(obj_one, &associativekey);
    self.textField.text = associativeObj;
}


- (IBAction) cutAssociative
{
    objc_setAssociatedObject(obj_one, &associativekey, nil, OBJC_ASSOCIATION_RETAIN);
    [self getAssociativeValue];
}

OC对象关联~objc_setAssociatedObject/objc_getAssociatedObject_第1张图片



完整的项目链接:https://github.com/lizhongfu/AssociativeDemo

转载请保留,原文链接:http://write.blog.csdn.net/postedit/8784152

若发现有不合适或错误之处,还请批评指正,不胜感激。



你可能感兴趣的:(OC对象关联~objc_setAssociatedObject/objc_getAssociatedObject)