2015-07-05 25 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元素(以及执行时间,内存等)的消息。

相关问题