删除按名称使用闭包语法创建的 NotificationCenter 观察者是否足够? [英] Is removing a NotificationCenter observer that was created with closure syntax by name adequate?

查看:57
本文介绍了删除按名称使用闭包语法创建的 NotificationCenter 观察者是否足够?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用块/尾随闭包语法创建的通知,如下所示:

I have a few notifications that were created using block / trailing closure syntax which look like this:

NotificationCenter.default.addObserver(forName: .NSManagedObjectContextObjectsDidChange, object: moc, queue: nil) { note in
    // implementation
}

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

Which I was later removing by name, like this:

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

我的问题

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

My Question

Is this adequate? Or do I absolutely need to save the NSObjectProtocol to it's own property and remove that property with the following syntax?

NotificationCenter.default.removeObserver(didChangeNotification)

推荐答案

您绝对需要将返回值存储在一个属性中并稍后将其删除.

You absolutely need to store the return value in a property and remove that later on.

来自 https://developer.apple.com/reference/foundation/nsnotificationcenter/1411723-addobserverforname:

充当观察者的不透明对象.

Return Value

An opaque object to act as the observer.

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

When you call any one of the removeObserver methods, the first parameter is the observer to remove. When you set up a block to respond to a notification, self is not the observer, NSNotificationCenter creates its own observer object behind the scenes and returns it to you.

注意:从 iOS 9 开始,您不再需要从 dealloc/deinit 调用 removeObserver,因为当观察者离开时这会自动发生.因此,如果您只针对 iOS 9,这可能会正常工作,但如果您根本不保留返回的观察者,则通知可能会在您预期之前被删除.安全总比后悔好.

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.

这篇关于删除按名称使用闭包语法创建的 NotificationCenter 观察者是否足够?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆