2015-08-18 77 views
1

我的viewController以及內側的viewDidLoad中我有斯威夫特 - 通知觀察者多次調用

NSNotificationCenter.defaultCenter().addObserver(self, selector: "showNextQuestions", name: "showNextQuestionsID", object: nil) 

在另一個控制器我有

NSNotificationCenter.defaultCenter().postNotificationName("showNextQuestionsID", object: nil) 

如果我從應用回家並啓動它再次發揮作用showNextQuestionID觸發兩次。

我試圖用

func applicationDidEnterBackground(application: UIApplication) { 
    NSNotificationCenter.defaultCenter().removeObserver(self, name: "showNextQuestionsID", object: nil) 
} 

但是,這並沒有幫助,

和的viewController

deinit { 
    NSNotificationCenter.defaultCenter().removeObserver(self) 
} 

我該如何解決這個問題?

回答

2

您沒有在正確的位置刪除您的通知觀察員。你在你的視圖控制器子類中註冊觀察者,你需要在同一個類中刪除它。一個合乎邏輯的地方是重寫viewWillDisappear方法。將下面的代碼在您的視圖控制器子類:

override func viewWillDisappear(_ animated: Bool) { 
    super.viewWillDisappear(animated) 

    NSNotificationCenter.defaultCenter().removeObserver(self) 
} 

同時刪除

NSNotificationCenter.defaultCenter().removeObserver(self, name: "showNextQuestionsID", object: nil) 

從AppDelegate中。當你在AppDelegate中提供'self'參數時,它指的是AppDelegate類,而不是你的視圖控制器。當您調用視圖控制器sublcass中的通知觀察者時,self是您的視圖控制器,這正是您想要的。

最後,當您僅調用removeObserver(self)而沒有其他參數時,它將取消註冊該對象的所有觀察者。這樣你就不必通過名字列出每個觀察者。

+1

是否有另一種方式是不viewWillDisappear?我需要在ViewController中更改UI,其中observer在其他控制器上的用戶註冊時進行註冊。在用戶到達此處之前,必須更換控制器 –

0

將您的觀察者放在AppDelegate或單例中,以便在應用程序狀態期間輕鬆添加和刪除觀察者。

0

applicationDidEnterBackground and deinit應該沒問題。

問題是您嘗試刪除applicationDidEnterBackground中的觀察者的方式。您試圖從AppDelegate中移除觀察者,並且需要從ViewController中移除觀察者。

要解決該問題:

1)在您的視圖控制器傾聽UIApplicationDidEnterBackgroundNotification時:

func init() { 
    super.init() 

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "myAppDidEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil) 
} 

2)實施聽UIApplicationDidEnterBackgroundNotification

func myAppDidEnterBackground() { 
NSNotificationCenter.defaultCenter().removeObserver(self, name: "showNextQuestionsID", object: nil) 
} 

3)額外的方法。你也可以聽UIApplicationWillEnterForegroundNotification爲了再次添加您的自定義通知