鍍金池/ 問答/C  iOS/ iOS這種觀察者如何移除?

iOS這種觀察者如何移除?

下面這段添加觀察者的代碼:

// 鍵盤隱藏
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification
                                                  object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note)
 {
     // 更新約束
     [self.scrollView mas_updateConstraints:^(MASConstraintMaker *make) {
         make.bottom.mas_equalTo(self.view);
     }];
     [self.associationTableView mas_updateConstraints:^(MASConstraintMaker *make) {
         make.bottom.mas_equalTo(self.view);
     }];
 }];

如何移除添加的觀察者?

我試了:

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

以及

[[NSNotificationCenter defaultCenter] removeObserver:_observer1 name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:_observer2 name:UIKeyboardWillHideNotification object:nil];

(_observer1_observer2addObserverForName方法的返回值)

上面兩種方法都沒有移除添加的觀察者,導(dǎo)致視圖控制器沒走dealloc。

這種觀察者該如何移除?

回答
編輯回答
你好胸

同意
Chris 的看法

2018年2月23日 02:25
編輯回答
青黛色

視圖控制器沒走dealloc不是沒有移除觀察者, 而是NSNotificationCenter這個對象方法 addObserverForName的block強引用self, 你改成弱引用試試.

2017年11月10日 08:17
編輯回答
荒城

這段代碼是寫在VC里邊了吧?
應(yīng)該是有內(nèi)存泄漏吧?
VC有成功執(zhí)行dealloc()嗎?
解決辦法:weak-strong dance

2017年8月13日 07:22