-2

我最近查看了一些快速代码,发现了这一点:添加观察者,然后立即将其删除。这背后的逻辑是什么?

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) {
4

1 回答 1

1

因为就程序执行时间而言,它不是“马上”。一些观察者对对象的生命周期进行监听是有意义的(在这种情况下是视图控制器)。其他的仅在 VC 可见时才适用——例如,当您看不到它们时,您无需侦听旨在更新 UI 元素(并占用执行时间、内存等)的消息。

于 2015-07-05T23:41:13.803 回答