2015-07-05 69 views
-2

之後立即刪除它我最近查看了一些swift代碼,我發現這個:添加觀察者,然後立即刪除它。那背後的邏輯是什麼?爲什麼添加一個oberver在

override func viewDidAppear(animated: Bool) { 
    super.viewDidAppear(animated) 
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "displayPushMessage:", name: "displayMessage", object: nil) 

} 

//adding the observer and removing it right after whhy?? where is the logic 

override func viewDidDisappear(animated: Bool) { 
    super.viewDidDisappear(animated) 
    NSNotificationCenter.defaultCenter().removeObserver(self, name: "displayMessage", object: nil) 
} 

func displayPushMessage (notification:NSNotification) { 
+1

爲什麼你認爲觀察者在被添加後被刪除? – rmaddy

回答

1

因爲在程序執行時間方面它不是「正確的」。一些觀察者有意義地傾聽對象的生命週期(在這種情況下視圖控制器)。其他只適用於VC可見的情況 - 例如,您不需要偵聽其目的是在無法看到它們時更新UI元素(以及執行時間,內存等)的消息。

相關問題