0%

Associated Objects 关联对象

Associated Objects 介绍

<objc/runtime.h> 中的函数号称是iOS中最后一把神兵利刃,具有其他方式做不到的,能为应用和框架提供强大功能的能力。但使用不当也可能废掉代码的,一切代码和逻辑都可能被异常糟糕的副作用影响。

就像和魔鬼做交易一样常常让人怀着巨大的恐惧。

历史

对象关联(或称为关联引用)本来是 Objective-C 2.0 运行时的一个特性,起始于 OS X Snow LeopardiOS4

核心函数 3 个 – 允许将任何键值在允许时关联到对象上

  • objc_setAssociatedObject
  • objc_getAssociatedObject
  • objc_removeAssociatedObjects

这有什么用呢?这允许开发者对已经存在的类在扩展中添加自定义的属性

实现的 3 种方式

  • static char
  • selector
  • _cmd_

使用 static char 实现

NSObject+AssociatedObject.h

1
2
3
@interface NSObject (AssociatedObject)
@property (nonatomic, strong) id associatedObject;
@end

NSObject+AssociatedObject.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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

使用 selector 实现

NSObject+AssociatedObject.h

1
2
3
@interface NSObject (AssociatedObject)
@property (nonatomic, strong) id associatedObject;
@end

NSObject+AssociatedObject.m

1
2
3
4
5
6
7
8
9
10
11
12
13
@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

使用 _cmd_ 实现

NSObject+AssociatedObject.h

1
2
3
@interface NSObject (AssociatedObject)
@property (nonatomic, strong) id associatedObject;
@end

NSObject+AssociatedObject.m

1
2
3
4
5
6
7
8
9
10
11
12
13
@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 的关联观察者。

应用举例

UIImagePickerController 图片选择回调

关联一个 block 实现完成选择图片后的回调。

UIImagePickerController+RFBlocks.h

1
2
3
4
5
6
7
8
9
@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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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

使用:

1
2
3
4
5
6
7
8
9
__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];

或者

1
2
3
4
5
6
7
8
9
10
11
12
13
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];

UIButton 按钮事件回调

关联一个按钮事件 block,当触发按钮 UIControlEventTouchUpInside 事件时回调。

UIButton+RFBlcoks.h
1
2
3
4
5
6
7
@interface UIButton (RFBlcoks)

typedef void(^RFButtonClickBlock)(UIButton *button);

@property (nonatomic, copy) RFButtonClickBlock rf_buttonClickBlock;

@end
UIButton+RFBlcoks.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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

使用:

1
2
3
self.button.rf_buttonClickBlock = ^(UIButton *button){
NSLog(@"%@ clicked",button);
};

Demo 地址:

参考资料: