objc_getAssociatedObject objc_setAssociatedObject关联
关联是指把两个对象相互关联起来,使得其中的一个对象作为另外一个对象的一部分。
创建关联要使用到Objective-C的运行时函数:objc_setAssociatedObject来把一个对象与另外一个对象进行关联。该函数需要四个参数:源对象,关键字,关联的对象和一个关联策略。
用法:
NSObject *object=[[NSObject alloc] init];
static char associatekey;
objc_setAssociatedObject(object, &associatekey, @"object value", OBJC_ASSOCIATION_ASSIGN);
获得关联对象
NSString * associatedObject = (NSString *)objc_getAssociatedObject(object, &associatekey);
断开关联
objc_setAssociatedObject(object, &associatekey, nil, OBJC_ASSOCIATION_ASSIGN);
需要导入#import <objc/runtime.h>
下面是完整的例子
#import <Foundation/Foundation.h> @property (nonatomic,copy) NSString *stuName; @end
#import "Student.h" @implementation Student @end |
#import "Student.h" @interface Student (StudentCategory) @property (nonatomic,copy) NSString *nickName; @end
//objc_getAssociatedObject 是在runtime下的,所以必须导入runtime库。 @implementation Student (StudentCategory)
// objc_setAssociatedObject 用在category里面的property, category里面的property必须要手动实现getter和setter方法。 -(void)setNickName:(NSString *)value
|