在开发过程中,经常会使用KVO做一些业务监听,比如监听列表的滑动位置,获取webView的加载进度和网页标题等等。通常的使用情况是在需要使用的地方添加监听者,使用完成后移除监听者,移除的操作我们经常放在dealloc()方法中执行。
但是也会遇到问题,比如偶尔忘记了释放,或者多次释放,会造成程序崩溃,极度影响用户体验。
那么如何写一个不需要移除监听者的KVO呢,就是我们今天探讨的话题。
举例:PMPerson类有一个属性age,再点击View时,更改age的值。
首先看一下我们正常的使用情况,:
@interface PMPerson : NSObject
@property (nonatomic, assign) NSInteger age;
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
[self.person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
NSLog(@"object:%@-----newValue:%zd",object,self.person.age);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.person.age = random() % 100;
}
- (PMPerson *)person
{
if (!_person) {
_person = [[PMPerson alloc]init];
}
return _person;
}
@end
从第一个页面页面进入时的代码大家可以自行实现。现在在每次点击View时,都会随机更改person的值,如果这时候离开当前页面,就会报如下错误:
'An instance 0x17000e020 of class PMPerson was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x17003f9a0>
在测试时候,发现只有iOS10的系统会崩溃,iOS10 以上的没有出现这个问题。查看官方文档,依旧提示需要在不使用的时候移除监听者,就按照常规的方法来移除。
为了避免崩溃,一般在dealloc方法中来进行移除,如下:
- (void)dealloc
{
NSLog(@"%s",__func__);
[_person removeObserver:self forKeyPath:@"age"];
}
我们今天的任务就是来研究一下,怎么能在不写这句代码的情况下,依旧保证程序可以正常运行。
先看我们的解决方案:
- 添加一个NSObject的KVO分类,在分类中实现addObserver:forKeyPath:方法。
- 在添加观察者过程中,实现一个中间类,需要注意两个要点
1.同时将中间类作为target的属性,当target释放时,中间类作为属性也会自动释放。
2.中间类对target实现弱引用,使用unsafe_unretained关键字实现。
3.当中间类触发dealloc时,在中间类的dealloc方法中实现移除观察者方法。
代码如下:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface PMKVOProxy : NSObject
@property (nonatomic, unsafe_unretained) id unsafe_unretainedTarget;
@property (nonatomic, unsafe_unretained) id unsafe_unretainedObserver;
@property (nonatomic, strong) NSString *keyPath;
@property (nonatomic, weak) ObserverHelper *factor;
@end
@implementation PMKVOProxy
- (void)dealloc
{
NSLog(@"%s",__func__);
[self.unsafe_unretainedTarget removeObserver:self.unsafe_unretainedObserver forKeyPath:self.keyPath];
}
@end
#import "NSObject+KVO.h"
@implementation NSObject (KVO)
- (void)pm_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
{
[self addObserver:observer forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:nil];
ObserverHelper *helper = [ObserverHelper new];
ObserverHelper *sub = [ObserverHelper new];
sub.target = helper.target = self;
sub.observer = helper.observer = observer;
sub.keyPath = helper.keyPath = keyPath;
helper.factor = sub;
sub.factor = helper;
const char *helpeKey = [[keyPath mutableCopy] UTF8String];
const char *subKey = [[keyPath mutableCopy] UTF8String];
// 关联属性 举例 self 和 helper 关联 当self释放的时候 helper释放 即可释放self的kvo 观察者和sub关联 当观察者释放的时候 调用sub的移除同样也能删除self的kvo factor是同一个对象 是为防止多次移除导致的崩溃
objc_setAssociatedObject(self, helpeKey, helper, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(observer, subKey, sub, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
在使用过程中只需要实现以下替换,就可以解决没有移除观察者造成的崩溃了。
[self.person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
改为
[self.unsafe_unretainedTarget removeObserver:self.unsafe_unretainedObserver forKeyPath:self.keyPath];
最后想再补充一点内存管理方面的知识点:
注意:修饰target和observer使用的是unsafe_unretain关键字。如果使用weak修饰时,同样会引起崩溃。
1.unsafe_unretain在释放后,指针仍指向原来的地址,不会被释放,所以是不安全的;
2.weak修饰的对象在释放后,指针指向的地址会被置为空,是安全的。
假如改为weak修饰tagert时候,由于对象置空,给空对象发送移除监听者的消息,是不会成功的,所以程序依旧会崩溃。
假如使用weak修饰observer,由于observer置空,会报移除的监听者不能为空的错误。
所以target和observer都使用unsafe_unretained修饰就可以解决以上问题。