通过runtime的两种方法就可以为类别添加一个实例变量了。
#import <Foundation/Foundation.h>
@interface NSObject (IndieBandName)
@property (nonatomic, copy) NSString *indieBandName;
@end
#import "NSObject+IndieBandName.h"
#import <objc/runtime.h>
//设置关联的key
static const void *IndieBandNameKey = &IndieBandNameKey;
@implementation NSObject (IndieBandName)
- (NSString *)indieBandName {
return objc_getAssociatedObject(self, IndieBandNameKey);
}
- (void)setIndieBandName:(NSString *)indieBandName{
//Associated关联
objc_setAssociatedObject(self, IndieBandNameKey, indieBandName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
网友评论