Associated Objects 介绍
<objc/runtime.h>
中的函数号称是iOS中最后一把神兵利刃,具有其他方式做不到的,能为应用和框架提供强大功能的能力。但使用不当也可能废掉代码的,一切代码和逻辑都可能被异常糟糕的副作用影响。
就像和魔鬼做交易一样常常让人怀着巨大的恐惧。
历史
对象关联(或称为关联引用)本来是Objective-C 2.0
运行时的一个特性,起始于OS X Snow Leopard
和iOS4
。
核心函数3个 -- 允许将任何键值在允许时关联到对象上
- objc_setAssociatedObject
- objc_getAssociatedObject
- objc_removeAssociatedObjects
这有什么用呢?这允许开发者对已经存在的类在扩展中添加自定义的属性
实现的3种方式
static char
selector
_cmd_
1.使用 static char
实现
NSObject+AssociatedObject.h
@interface NSObject (AssociatedObject)
@property (nonatomic, strong) id associatedObject;
@end
NSObject+AssociatedObject.m
@implementation NSObject (AssociatedObject)
static char kAssociatedObjectKey;
- (id)associatedObject
{
return objc_getAssociatedObject(self,&kAssociatedObjectKey);
}
- (void)setAssociatedObject:(id)associatedObject
{
objc_setAssociatedObject(self, &kAssociatedObjectKey, associatedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
2.使用 selector
实现
NSObject+AssociatedObject.h
@interface NSObject (AssociatedObject)
@property (nonatomic, strong) id associatedObject;
@end
NSObject+AssociatedObject.m
@implementation NSObject (AssociatedObject)
- (id)associatedObject
{
return objc_getAssociatedObject(self, @selector(associatedObject));
}
- (void)setAssociatedObject:(id)associatedObject
{
objc_setAssociatedObject(self, @selector(associatedObject), associatedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
2.使用 _cmd_
实现
NSObject+AssociatedObject.h
@interface NSObject (AssociatedObject)
@property (nonatomic, strong) id associatedObject;
@end
NSObject+AssociatedObject.m
@implementation NSObject (AssociatedObject)
- (id)associatedObject
{
return objc_getAssociatedObject(self, _cmd_);
}
- (void)setAssociatedObject:(id)associatedObject
{
objc_setAssociatedObject(self, @selector(associatedObject), associatedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
关联对象的行为
属性根据枚举类型objc_AssociationPolicy
来决定被关联在对象上的行为:
Behavior | 与之等效的@property |
---|---|
OBJC_ASSOCIATION_ASSIGN | @property (assign) 或@property (unsafe_unretained) |
OBJC_ASSOCIATION_RETAIN_NONATOMIC | @property (nonatomic, strong) |
OBJC_ASSOCIATION_COPY_NONATOMIC | @property (nonatomic, copy) |
OBJC_ASSOCIATION_RETAIN | @property (atomic, strong) |
OBJC_ASSOCIATION_COPY | @property (atomic, copy) |
OBJC_ASSOCIATION_ASSIGN
类型关联对象的弱引用不代表weak的弱引用,行为上更像unsafe_unretained
属性。
对象销毁时间
被关联的对象在声明周期内比对象本身释放要晚很多,在对象调用-dealloc
中的object_dispose()
中释放。
删除属性
你或许想要使用objc_removeAssociatedObjects()
来进行删除操作,但官方文档不建议手动调用这个函数。
这个函数可能会把其他用户对其添加的属性也移除了,正确的方式是调用objc_setAssociatedObject
方法,传入nil
值来清楚一个关联。
优秀样例
- 添加私有属性用于更好地去实现细节。
- 添加public属性来增强category的功能。
- 创建一个用于KVO的关联观察者。
应用举例
1.UIImagePickerController 图片选择回调
关联一个block实现完成选择图片后的回调。
UIImagePickerController+RFBlocks.h
@interface UIImagePickerController (RFBlocks)<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
typedef void(^RFImagePickerFinishBlock)(NSDictionary *info);
@property (nonatomic, copy) RFImagePickerFinishBlock rf_finishBlock;
+ (UIImagePickerController *)rf_imagePickerWithFinishBlock:(RFImagePickerFinishBlock)finishBlock;
@end
UIImagePickerController+RFBlocks.m
static const char kFinishBlockKey;
@implementation UIImagePickerController (RFBlocks)
+ (UIImagePickerController *)rf_imagePickerWithFinishBlock:(RFImagePickerFinishBlock)finishBlock
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.rf_finishBlock = finishBlock;
return picker;
}
- (RFImagePickerFinishBlock)rf_finishBlock {
return objc_getAssociatedObject(self, &kFinishBlockKey);
}
- (void)setRf_finishBlock:(RFImagePickerFinishBlock)rf_finishBlock {
self.delegate = self;
objc_setAssociatedObject(self, &kFinishBlockKey, rf_finishBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
RFImagePickerFinishBlock block = self.rf_finishBlock;
if (block) block(info);
[self dismissViewControllerAnimated:YES completion:nil];
self.rf_finishBlock = nil;
}
@end
使用:
__weak typeof(self)weakSelf = self;
UIImagePickerController *picker = [UIImagePickerController rf_imagePickerWithFinishBlock:^(NSDictionary *info) {
NSLog(@"finish picke image\n info:%@",info);
UIImage *img = info[@"UIImagePickerControllerOriginalImage"];
weakSelf.view.layer.contents = (id)img.CGImage;
}];
[self presentViewController:picker animated:YES completion:nil];
或者
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
__weak typeof(self)weakSelf = self;
picker.rf_finishBlock = ^(NSDictionary *info) {
NSLog(@"finish picke image\n info:%@",info);
UIImage *img = info[@"UIImagePickerControllerOriginalImage"];
weakSelf.view.layer.contentsGravity = kCAGravityResizeAspect;
weakSelf.view.layer.contents = (id)img.CGImage;
};
[self presentViewController:picker animated:YES completion:nil];
1.UIButton 按钮事件回调
关联一个按钮事件block,当触发按钮UIControlEventTouchUpInside
事件时回调。
UIButton+RFBlcoks.h
@interface UIButton (RFBlcoks)
typedef void(^RFButtonClickBlock)(UIButton *button);
@property (nonatomic, copy) RFButtonClickBlock rf_buttonClickBlock;
@end
UIButton+RFBlcoks.m
static char kButttonClickBlockKey;
@implementation UIButton (RFBlcoks)
- (RFButtonClickBlock)rf_buttonClickBlock
{
return objc_getAssociatedObject(self, &kButttonClickBlockKey);
}
- (void)setRf_buttonClickBlock:(RFButtonClickBlock)rf_buttonClickBlock
{
objc_setAssociatedObject(self, &kButttonClickBlockKey, rf_buttonClickBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonClicked
{
if (self.rf_buttonClickBlock) {
self.rf_buttonClickBlock(self);
}
}
@end
使用:
self.button.rf_buttonClickBlock = ^(UIButton *button){
NSLog(@"%@ clicked",button);
};
Demo地址:
原文发表于王若风的技术博客
参考资料:
- Associated Objects -- NSHipster
- Objective-C Associated Objects -- King's Cocoa
- Objective-C Associated Objects 的实现原理-- 雷纯峰的技术博客
- Associated Objects by Example -- Sebastian Rehnby