一定要在 类别中添加实例变量怎么办
那我偏偏想要在类别中添加实例变量该怎么办呢?这时候就要用到runtime了,不要忘记了Objective-C是动态语言。一种常见的办法是通过runtime.h中objc_getAssociatedObject / objc_setAssociatedObject
来访问和生成关联对象。这两个方法可以让一个对象和另一个对象关联,就是说一个对象可以保持对另一个对象的引用,并获取那个对象。
//NSObject+IndieBandName.h @interface NSObject (IndieBandName) @property (nonatomic, strong) NSString *indieBandName; @end
// NSObject+IndieBandName.m #import "NSObject+Extension.h" #import <objc/runtime.h>
static const void *IndieBandNameKey = &IndieBandNameKey;
@implementation NSObject (IndieBandName)
@dynamic indieBandName;
- (NSString *)indieBandName {
return objc_getAssociatedObject(self, IndieBandNameKey);
}
- (void)setIndieBandName:(NSString *)indieBandName {
objc_setAssociatedObject(self, IndieBandNameKey, indieBandName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
参考:
https://blog.csdn.net/intheair100/article/details/72718625
http://www.cnblogs.com/crazypebble/p/3439261.html
http://quotation.github.io/objc/2015/05/21/objc-runtime-ivar-access.html
http://www.cnblogs.com/wupher/archive/2013/01/05/2845338.html