@interface Person (AddAttribute)
@property(nonatomic,strong)NSString *age;
@property(nonatomic,assign)NSUInteger age2;
@end
基本数据类型需要转换,此外,static NSString *ageKey = @"ageKey";
只需要当做一个地址中转站即可
static NSString *ageKey2 = @"ageKey2";
#import "Person+AddAttribute.h"
#import <objc/runtime.h>
static NSString *ageKey = @"ageKey";
static NSString *ageKey2 = @"ageKey2";
@implementation Person (AddAttribute)
-(void)setAge:(NSString *)age{
objc_setAssociatedObject(self, &ageKey, age, OBJC_ASSOCIATION_RETAIN);
}
-(NSString *)age{
return objc_getAssociatedObject(self, &ageKey);
}
-(void)setAge2:(NSUInteger)age2{
objc_setAssociatedObject(self, &ageKey2, @(age2), OBJC_ASSOCIATION_ASSIGN);
}
-(NSUInteger)age2{
NSNumber *numVaue = objc_getAssociatedObject(self, &ageKey2);
return [numVaue integerValue];
}