在.h文件里添加属性
@interface NSObject (IndieBandName)
@property (nonatomic, copy) NSString *myString;
@property (nonatomic,assign) NSInteger intData;
@end
在.m文件里添加getter和setter方法
记得添加运行时的支持库:
#import <objc/runtime.h>文件
static const void *myStringKey = &myStringKey;
static const void *intValueKey = &intValueKey;
//添加String类型的属性变量
- (NSString *)myString
{
return objc_getAssociatedObject(self, myStringKey);
}
- (void)setMyString:(NSString *)myString
{
objc_setAssociatedObject(self, myStringKey, myString, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
//添加NSInteger类型变量
- (NSInteger)intData
{
return [objc_getAssociatedObject(self, intValueKey) integerValue];
}
- (void)setIntData:(NSInteger)intData
{
NSNumber *number = [NSNumber numberWithInteger:intData];
objc_setAssociatedObject(self, intValueKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}