一 定义一个类
Student.h文件
@interface Student : NSObject
@property (nonatomic,assign) NSInteger age;
@end
Student.m文件
@implementation Student
@end
二 定义分类
import "Student.h"
@interface Student (Extention)
@property (nonatomic,copy) NSString *name;
@property (nonatomic,assign) NSInteger height;
@end
import "Student+Extention.h"
import <objc/runtime.h>
static char *nameKey = "nameKey";
static char *heightKey = "heightKey";
@implementation Student (Extention)
- (void)setName:(NSString*)name{
objc_setAssociatedObject(self, nameKey, name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)name{
return objc_getAssociatedObject(self, nameKey);
}
- (void)setHeight:(NSInteger)height{
objc_setAssociatedObject(self, heightKey, @(height), OBJC_ASSOCIATION_ASSIGN);
}
- (NSInteger)height{
return [objc_getAssociatedObject(self, heightKey) integerValue];
}
@end
三 说明
/*
OBJC_ASSOCIATION_ASSIGN; //assign策略
OBJC_ASSOCIATION_COPY_NONATOMIC; //copy策略
OBJC_ASSOCIATION_RETAIN_NONATOMIC; // retain策略
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);
*/
四 注意事项
需包含 #import <objc/runtime.h> 头文件