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>
@class Address;
@interface Student : NSObject

@property (nonatomic,copy) NSString *stuName;
@property (nonatomic,assign) NSInteger age;
@property (nonatomic,weak) Address *address;

@end

 

#import "Student.h"

@implementation Student

@end

 

#import "Student.h"

@interface Student (StudentCategory)

@property (nonatomic,copy) NSString *nickName;

@end

 


#import "Student+StudentCategory.h"

//objc_getAssociatedObject 是在runtime下的,所以必须导入runtime库。
#import <objc/runtime.h>

@implementation Student (StudentCategory)

 

// objc_setAssociatedObject 用在category里面的property, category里面的property必须要手动实现getter和setter方法。
-(NSString*)nickName
{
/*
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);
*/



//category不会自动合成实例变量_nickName,所以不能直接return _nickName;
return objc_getAssociatedObject(self,@selector(nickName));
}

-(void)setNickName:(NSString *)value
{
//category不会自动合成实例变量_nickName,所以不能直接_nickName=value;
objc_setAssociatedObject(self, @selector(nickName), value, OBJC_ASSOCIATION_COPY_NONATOMIC);
}


@end

 

posted on 2015-12-28 15:45  StanleyZhang  阅读(215)  评论(0编辑  收藏  举报