首先分类中如果直接声明属性是没有任何意义的,我们需要手动实现set和get方法,通过运行时:
@interface Person : NSObject @property (assign, nonatomic) NSInteger age; -(void)run; @end #import "Person.h" @implementation Person -(void)run{ NSLog(@"%s",__func__); } @end
#import "Person.h" @interface Person (Extention) @property (copy, nonatomic) NSString *name; -(void)saySex; @end #import "Person+Extention.h" #import <objc/runtime.h> @implementation Person (Extention) //定义常量 必须是C语言字符串 static char *PersonNameKey = "PersonNameKey"; -(void)setName:(NSString *)name{ /* OBJC_ASSOCIATION_ASSIGN; //assign策略 OBJC_ASSOCIATION_RETAIN_NONATOMIC; // retain策略 OBJC_ASSOCIATION_COPY_NONATOMIC; //copy策略 OBJC_ASSOCIATION_RETAIN; OBJC_ASSOCIATION_COPY; */ /* * id object 给哪个对象的属性赋值 const void *key 属性对应的key id value 设置属性值为value objc_AssociationPolicy policy 使用的策略,是一个枚举值,和copy,retain,assign是一样的,手机开发一般都选择NONATOMIC objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy); */ objc_setAssociatedObject(self, PersonNameKey, name, OBJC_ASSOCIATION_COPY_NONATOMIC); } -(NSString *)name{ return objc_getAssociatedObject(self, PersonNameKey); } -(void)saySex{ NSLog(@"%s----%@",__func__,self); } @end
原文:http://www.cnblogs.com/zhaoyunboy/p/add-property-to-category-by-runtime.html