ios - 何时为 nsnotificationcenter 调用 removeObserver

标签 ios swift nsnotificationcenter nsnotifications nsnotification

我有一个带有按钮操作的 View Controller :

@IBAction func MultiplayerButtonClick(sender: AnyObject) {
            NSNotificationCenter.defaultCenter().addObserver(
              self, 
              selector: NotificationConstants.pvpConnEstablishedSelector, 
              name: NotificationConstants.pvpConnEstablishedString , 
              object: nil)

            setUpGameScene()
            initiateMultiplayerGC()
    }

在某处,发布了一条通知,触发了该观察者的选择器:

//action for pvpConnEstablishedSelector
func hideMainView() {
   MenuView.hidden = true
   //NSNotificationCenter.defaultCenter().removeObserver(self) ???
}

在作为观察者选择器的函数中调用 removeObserver 是否合适?

或者有没有更合适的地方做这个?

最佳答案

一些观察:

  1. 我从您的代码注释中推断出您正在考虑为该特定通知移除选择器内的观察者。这是一个很好的做法。

    我会很小心地调用 removeObserver ,但是,因为这将删除您可能已设置的所有观察者。如果您在作为特定通知的选择器的例程中调用它,那么我可能倾向于只删除该特定通知:

    NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationConstants.pvpConnEstablishedString, object: nil)
    

    是的,在这一点上,你可能只观察到一个通知,所以这可能感觉没有必要,但如果在未来某个时候你为不同的通知添加完全独立的通知处理代码,你要确保你没有' 在处理特定通知时不小心删除了所有观察者。

  2. 您可能希望注意在通知到来之前此 View Controller 可能被关闭的可能性。在这种情况下,还添加 removeObserver 可能是明智的。在deinit View Controller 的方法。

    在这种情况下,简单的 removeObserver(self)是谨慎的(因为在释放 View Controller 时删除所有观察者是合理的)。

关于ios - 何时为 nsnotificationcenter 调用 removeObserver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32511277/

相关文章:

ios - pod WEPopover 弹出菜单未显示为 currentTopViewcontroller。相反,它会转到 currentTopviewController View 层次结构的后面

swift - 单独类中的数据源 - 未调用 cellForRowAt indexPath

swift - 如何在 OS X 中的虚拟桌面之间移动应用程序窗口?

objective-c - 应用程序将终止 : NSNotificationCenter vs Application Delegate

ios - 从检测到的信标中检索对象

ios - Facebook Graph 请求无法在 iOS 9.2 中检索电子邮件 - xCode 7

ios - 如何在 CALayer 中为图像制作动画

Swift NSScrollView 更好的 NSViewBoundsDidChangeNotification 观察?

iphone - 我可以观看另一个类(class)的 NSNotification 吗?

ios - 如何更改永远运行的 SKAction