簡體   English   中英

觀察者永遠不會從NSNotificationCenter中刪除

[英]Observer never gets removed from NSNotificationCenter

我正在添加一個視圖控制器作為UIKeyboardWillShowNotification通知的觀察者。

我在viewDidLoad有這個代碼:

[[NSNotificationCenter defaultCenter] addObserver:self
                                     selector:@selector(keyboardWillShow:)
                                         name:UIKeyboardWillShowNotification
                                       object:nil];

在我的dealloc

[[NSNotificationCenter defaultCenter] removeObserver:self];

即使在視圖控制器關閉時調用dealloc也不會刪除觀察者。 因此,當我第二次打開它時,NSNotificationCenter將嘗試通知已發布的舊對象,並且應用程序崩潰。

我在StackOverflow上看到了關於這個特殊問題的幾個問題,但沒有答案對我有用。

我已經嘗試在viewWillDisappearviewDidDisappear刪除觀察者,但同樣的問題發生了。

我正在使用ARC。

你有沒有在viewWillDisappear嘗試過這段精確的代碼?

- (void)viewWillDisappear:(BOOL)animated 
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

根據你的解釋,我認為問題不在於移除觀察者。 嘗試從另一個viewcontroller觸發Observer。 如果未觸發,您將知道刪除成功,並且在第二次添加觀察者時會出現問題。

也許嘗試通過指定之前設置的參數name ,如下所示:

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];

看起來觀察者已多次設置。 您的控制器是否繼承了同樣注冊相同通知的類? 這可能導致控制器實例多次注冊為觀察者。 作為一種解決方法嘗試這個,在你添加觀察者的控制器類中,

// Remove as observer first
[[NSNotificationCenter defaultCenter] removeObserver:self];
                                      name:UIKeyboardWillShowNotification
                                      object:nil];
// Then add
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(keyboardWillShow:)
                                      name:UIKeyboardWillShowNotification
                                      object:nil];

這將確保觀察者只被添加一次。

希望有所幫助!

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"name" object:nil];

它適用於我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM