使用KVO注意的問題

看下面的代碼

//設(shè)置眼睛

UIButton *button= [[UIButton alloc]initWithFrame: (CGRect){{self.width - self.height,0},{self.height,self.height}}];

button.backgroundColor = [UIColor redColor];

[button addTarget:self action:@selector(changePassWord) forControlEvents:UIControlEventTouchUpInside];

self.eyeButton = button;

self.eyeButton.hidden = YES;

//注冊(cè)監(jiān)聽者

[self.eyeButton addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew context:nil];

[self addSubview:button];

#pragma mark - 設(shè)置眼睛,如果設(shè)置的眼睛是顯示狀態(tài)那么就要進(jìn)行textField的寬度減少

/**

*? 監(jiān)聽者的響應(yīng)者事件

*

*? @param keyPath hidden

*? @param object? button

*? @param change? 值如果進(jìn)行改變

*? @param context

*/

- (void)observeValueForKeyPath:(NSString *)keyPath

ofObject:(id)object

change:(NSDictionary *)change

context:(void *)context {

if ([keyPath isEqualToString:@"hidden"] && object == self.eyeButton ) {

_textField.width = self.eyeButton.x - pixw(6);

_placeHolderLabel.width = _textField.width? ;

}

else

[super observeValueForKeyPath:keyPath? ofObject:object change:change? context: context];

}

-(void)dealloc

{

[self.eyeButton removeObserver:self forKeyPath:@"hidden"];

}

潛在的問題有可能出現(xiàn)在dealloc中對(duì)KVO的注銷上。KVO的一種缺陷(其實(shí)不能稱為缺陷,應(yīng)該稱為特性)是,當(dāng)對(duì)同一個(gè)keypath進(jìn)行兩次removeObserver時(shí)會(huì)導(dǎo)致程序crash,這種情況常常出現(xiàn)在父類有一個(gè)kvo,父類在dealloc中remove了一次,子類又remove了一次的情況下。不要以為這種情況很少出現(xiàn)!當(dāng)你封裝framework開源給別人用或者多人協(xié)作開發(fā)時(shí)是有可能出現(xiàn)的,而且這種crash很難發(fā)現(xiàn)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容