加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:25:25 所属栏目:百科 来源:网络整理
导读:我有一些使用块/尾随闭包语法创建的通知,如下所示: NotificationCenter.default.addObserver(forName: .NSManagedObjectContextObjectsDidChange,object: moc,queue: nil) { note in // implementation} 我后来删除了名字,如下所示: NotificationCenter.de
我有一些使用块/尾随闭包语法创建的通知,如下所示:
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读