iOS添加关联对象即可为分类间接添加成员变量
在分类中声明属性,只相当于声明了两个方法(set和get),不会生成成员变量和set/get方法的实现。
利用runtime的关联对象方法objc_setAssociatedObject(类,key,value,关联策略)
,同时手动实现set/get方法即可为分类添加属性。
例如分类:MJPerson+Test.h
#import "MJPerson.h"
@interface MJPerson (Test)
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) int weight;
@end
#import "MJPerson+Test.h"
#import <objc/runtime.h>
@implementation MJPerson (Test)
- (void)setName:(NSString *)name
{
objc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)name
{
// 隐式参数
// _cmd == @selector(name)
return objc_getAssociatedObject(self, _cmd);
}
- (void)setWeight:(int)weight
{
objc_setAssociatedObject(self, @selector(weight), @(weight), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (int)weight
{
// _cmd == @selector(weight)
return [objc_getAssociatedObject(self, _cmd) intValue];
}
如上即为MJPerson分类添加了两个属性。
网友评论