在開發(fā)過程中,經(jīng)常會(huì)使用KVO做一些業(yè)務(wù)監(jiān)聽,比如監(jiān)聽列表的滑動(dòng)位置,獲取webView的加載進(jìn)度和網(wǎng)頁標(biāo)題等等。通常的使用情況是在需要使用的地方添加監(jiān)聽者,使用完成后移除監(jiān)聽者,移除的操作我們經(jīng)常放在dealloc()方法中執(zhí)行。
但是也會(huì)遇到問題,比如偶爾忘記了釋放,或者多次釋放,會(huì)造成程序崩潰,極度影響用戶體驗(yàn)。
那么如何寫一個(gè)不需要移除監(jiān)聽者的KVO呢,就是我們今天探討的話題。
舉例:PMPerson類有一個(gè)屬性age,再點(diǎn)擊View時(shí),更改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
從第一個(gè)頁面頁面進(jìn)入時(shí)的代碼大家可以自行實(shí)現(xiàn)。現(xiàn)在在每次點(diǎn)擊View時(shí),都會(huì)隨機(jī)更改person的值,如果這時(shí)候離開當(dāng)前頁面,就會(huì)報(bào)如下錯(cuò)誤:
'An instance 0x17000e020 of class PMPerson was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x17003f9a0>
在測試時(shí)候,發(fā)現(xiàn)只有iOS10的系統(tǒng)會(huì)崩潰,iOS10 以上的沒有出現(xiàn)這個(gè)問題。查看官方文檔,依舊提示需要在不使用的時(shí)候移除監(jiān)聽者,就按照常規(guī)的方法來移除。
為了避免崩潰,一般在dealloc方法中來進(jìn)行移除,如下:
- (void)dealloc
{
NSLog(@"%s",__func__);
[_person removeObserver:self forKeyPath:@"age"];
}
我們今天的任務(wù)就是來研究一下,怎么能在不寫這句代碼的情況下,依舊保證程序可以正常運(yùn)行。
先看我們的解決方案:
- 添加一個(gè)NSObject的KVO分類,在分類中實(shí)現(xiàn)addObserver:forKeyPath:方法。
- 在添加觀察者過程中,實(shí)現(xiàn)一個(gè)中間類,需要注意兩個(gè)要點(diǎn)
1.同時(shí)將中間類作為target的屬性,當(dāng)target釋放時(shí),中間類作為屬性也會(huì)自動(dòng)釋放。
2.中間類對target實(shí)現(xiàn)弱引用,使用unsafe_unretained關(guān)鍵字實(shí)現(xiàn)。
3.當(dāng)中間類觸發(fā)dealloc時(shí),在中間類的dealloc方法中實(shí)現(xiàn)移除觀察者方法。
代碼如下:
#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];
// 關(guān)聯(lián)屬性 舉例 self 和 helper 關(guān)聯(lián) 當(dāng)self釋放的時(shí)候 helper釋放 即可釋放self的kvo 觀察者和sub關(guān)聯(lián) 當(dāng)觀察者釋放的時(shí)候 調(diào)用sub的移除同樣也能刪除self的kvo factor是同一個(gè)對象 是為防止多次移除導(dǎo)致的崩潰
objc_setAssociatedObject(self, helpeKey, helper, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(observer, subKey, sub, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
在使用過程中只需要實(shí)現(xiàn)以下替換,就可以解決沒有移除觀察者造成的崩潰了。
[self.person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
改為
[self.unsafe_unretainedTarget removeObserver:self.unsafe_unretainedObserver forKeyPath:self.keyPath];
最后想再補(bǔ)充一點(diǎn)內(nèi)存管理方面的知識(shí)點(diǎn):
注意:修飾target和observer使用的是unsafe_unretain關(guān)鍵字。如果使用weak修飾時(shí),同樣會(huì)引起崩潰。
1.unsafe_unretain在釋放后,指針仍指向原來的地址,不會(huì)被釋放,所以是不安全的;
2.weak修飾的對象在釋放后,指針指向的地址會(huì)被置為空,是安全的。
假如改為weak修飾tagert時(shí)候,由于對象置空,給空對象發(fā)送移除監(jiān)聽者的消息,是不會(huì)成功的,所以程序依舊會(huì)崩潰。
假如使用weak修飾observer,由于observer置空,會(huì)報(bào)移除的監(jiān)聽者不能為空的錯(cuò)誤。
所以target和observer都使用unsafe_unretained修飾就可以解決以上問題。