Student
@interface Student : NSObject
@property (nonatomic,assign) NSInteger age;
@end
@implementation Student
@end
Student + Category
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>
////定義成常量 用C語言
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);