IOS通过runtime给category添加属性

来源:互联网 发布:麒麟linux官网 编辑:程序博客网 时间:2024/04/26 19:31
在IOS中在类别category中是不可以扩展属性只可以扩展方法的.但是我们可以使用runtime的

objc_setAssociatedObject和objc_getAssociatedObject来给我们的类别扩展属性.

如下 类别声明:

@interface UIViewController (ZYCategoryPropertyAccessary)


@property (nonatomic ,strong)NSObject *person;


@property (nonatomic ,copy)NSString *name;


@property (nonatomic ,assign)NSInteger age;


@end

具体实现:

#import <objc/runtime.h>

@implementation UIViewController (ZYCategoryPropertyAccessary)


-(NSString *)name

{

    returnobjc_getAssociatedObject(self,_cmd);

}

-(void)setName:(NSString *)name

{

    objc_setAssociatedObject(self,@selector(name), name, OBJC_ASSOCIATION_COPY_NONATOMIC);

}


-(NSObject *)person

{

    returnobjc_getAssociatedObject(self,_cmd);

}

-(void)setPerson:(NSObject *)person

{

    objc_setAssociatedObject(self,@selector(person), person, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}


-(NSInteger)age

{

    return [objc_getAssociatedObject(self,_cmd) integerValue];

}

-(void)setAge:(NSInteger)age

{

    objc_setAssociatedObject(self,@selector(age), @(age),OBJC_ASSOCIATION_ASSIGN);

}


@end

这样我们就可以给在类别中添加属性了!


0 0