标签:interface property import policy
主要利用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
标签:interface property import policy
原文地址:http://jyb2014.blog.51cto.com/9155315/1569698