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

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

概述我有一些使用块/尾随闭包语法创建的通知,如下所示: NotificationCenter.default.addObserver(forName: .NSManagedObjectContextObjectsDidChange, object: moc, queue: nil) { note in // implementation} 我后来删除了名字,如下所示: Notificatio 我有一些使用块/尾随闭包语法创建的通知,如下所示:
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.

总结

以上是内存溢出为你收集整理的swift – 删除使用闭包语法创建的NotificationCenter观察者是否足够?全部内容,希望文章能够帮你解决swift – 删除使用闭包语法创建的NotificationCenter观察者是否足够?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1031185.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存