我有一些使用块/尾随闭包语法创建的通知,如下所示:
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
fromdealloc
/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.