原理部分来源博客:玉令天下的博客
例子部分来源博客:zuolingfeng简书
在 OS X 10.6 之后,Runtime系统让Objc支持向对象动态添加变量。涉及到的函数有以下三个:
void objc_setAssociatedObject ( id object, const void *key, id value, objc_AssociationPolicy policy );
id objc_getAssociatedObject ( id object, const void *key );
void objc_removeAssociatedObjects ( id object );
这些方法以键值对的形式动态地向对象添加、获取或删除关联值。其中关联政策是一组枚举常量:
enum {
OBJC_ASSOCIATION_ASSIGN = 0,
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
OBJC_ASSOCIATION_RETAIN = 01401,
OBJC_ASSOCIATION_COPY = 01403
};
具体应用:给Category绑定属性值
#import "UIImage+category.h"
static const void *tagKey = &tagKey;
@implementation UIImage (category)
- (NSString *)tag {
return objc_getAssociatedObject(self, tagKey);
}
- (void)setTag:(NSString *)tag {
objc_setAssociatedObject(self, tagKey, tag, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
访问属性
UIImage *image = [UIImage imageNamed:@""];
[image setTag:@"100"];
NSLog(@"tag:%@", [image tag]);