利用类别(Category)为对象添加”实例变量”
主要利用ObjectiveC的C API中函数:
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) id objc_getAssociatedObject(id object, const void *key)
原理详细参见官方的ObjectiveC Runtime Reference.
好了,现在直接写怎么做了.
1.在定义类别之前, 引入runtime.
#import <objc/runtime.h>
2.定义&实现类别(以UIView为例)
定义:
@interface UIView(AddVariables) @property (nonatomic, retain) NSString *viewName; @end
实现:
// 定义存取的Key static const char *viewNameKey = "viewNameKey"; @implementation UIView(AddVariables) // get方法 - (NSString *)viewName { return (NSString *)objc_getAssociatedObject(self, viewNameKey); } // set方法 - (void)setViewName:(NSString *)newViewNameKey { objc_setAssociatedObject(self, viewNameKey, newViewNameKey, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end
3.调用测试:
- (void)viewDidLoad { UIView *testView = [[UIView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:testView]; [testView release]; [testView setViewName:@"Nori's View"]; NSLog(@"[testView's newPropery]:%@", testView.viewName); [super viewDidLoad]; }
输出结果如下:
testView's newPropery:Nori's View
另外有几篇不错的文章关于类别和关联的
iOS学习系列 - 扩展机制category与associative
http://www.cnblogs.com/liping13599168/archive/2012/09/13/2682664.html
利用类别(Category)为对象添加”实例变量”
http://blog.csdn.net/qhexin/article/details/7692846
http://blog.csdn.net/zhangxingping/article/details/7619444