一 定義一個(gè)類
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 給哪個(gè)對(duì)象的屬性賦值
const void *key 屬性對(duì)應(yīng)的key
id value 設(shè)置屬性值為value
objc_AssociationPolicy policy 使用的策略,是一個(gè)枚舉值特石,和copy泡挺,retain裆泳,assign是一樣的,手機(jī)開發(fā)一般都選擇NONATOMIC
objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy);
*/
四 注意事項(xiàng)
需包含 #import <objc/runtime.h> 頭文件