swift – 删除使用闭包语法创建的NotificationCenter观察者是否足够?

我有一些使用块/尾随闭包语法创建的通知,如下所示:
NotificationCenter.default.addobserver(forName: .NSManagedobjectContextObjectsDidChange,object: moc,queue: nil) { note in
    // implementation
}

我后来删除了名字,如下所示:

NotificationCenter.default.removeObserver(self,name: NSNotification.Name.NSManagedobjectContextObjectsDidChange,object: moc)

我的问题

这够了吗?或者我是否绝对需要将NSObjectProtocol保存到它自己的属性并使用以下语法删除属性

NotificationCenter.default.removeObserver(didChangeNotification)
您绝对需要将返回值存储在属性中,稍后将其删除.

https://developer.apple.com/reference/foundation/nsnotificationcenter/1411723-addobserverforname开始:

Return Value

An opaque object to act as the observer.

当您调用removeObserver方法中的任何一个时,第一个参数是要删除的观察者.当您设置一个块来响应通知时,self不是观察者,NSNotificationCenter会在幕后创建自己的观察者对象并将其返回给您.

Note: as of iOS 9,you are no longer required to call removeObserver from dealloc/deinit,as that will happen automatically when the observer goes away. So,if you’re only targeting iOS 9,this may all just work,but if you’re not retaining the returned observer at all,the notification Could be removed before you expect it to be. Better safe than sorry.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...