Swift 5.1/Cocoa:如何在类中注册方法,而不是将self注册为通知观察者?
我可以通过传入self并引用同一类中的方法来建立观察者回调:Swift 5.1/Cocoa:如何在类中注册方法,而不是将self注册为通知观察者?,cocoa,swift5.1,Cocoa,Swift5.1,我可以通过传入self并引用同一类中的方法来建立观察者回调: func applicationDidFinishLaunching(_ aNotification: Notification) { DistributedNotificationCenter.default .addObserver( self,
func applicationDidFinishLaunching(_ aNotification: Notification) {
DistributedNotificationCenter.default
.addObserver(
self,
selector: #selector(notificationReceived),
name: NSNotification.Name(rawValue: "Hello"),
object: nil)
}
@objc func notificationReceived() {
print("I have received the notification!")
}
//...
在上述情况下,在发布通知时调用notificationReceived。但是,如果我想注册属于另一个类的回调,我不能这样做:
class Another {
@objc func notificationReceived() {
print("I have received the notification!")
}
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
let observer = Another()
DistributedNotificationCenter.default
.addObserver(
observer,
selector: #selector(observer.notificationReceived),
name: NSNotification.Name(rawValue: "Hello"),
object: nil)
}
为什么上述方法不起作用?我需要做什么才能将属于self以外对象的方法注册为回调?这与另一个类无关。它与对象生命周期有关 你说的是让observer=另一个,在下一个瞬间,didFinish方法结束了,你的另一个observer实例消失在一股烟雾中。所以通知中心没有人可以联系。没有机会收到任何通知;在这种情况发生之前,观察者已经离开了 事实上,以前这样做会导致崩溃,因为您带着一个悬空的指针离开了通知中心。现在你没有崩溃,但什么也没发生
self的情况并非如此,不是因为self是同一个类,而是因为它是应用程序委托,在应用程序的整个生命周期中都存在。分布式通知中心允许观察者消失在烟雾中的原因是该中心只保留了对观察者的弱引用,因此,一旦中心外的最后一个参考消失,观察者就会被释放。您可以在上的文档中看到,该文档表示接收器不保留notificationObserver。@BobGilmore,直到最近,弱表示非弧弱,因此我对崩溃的观点是。在取消分配观察员之前,取消其注册至关重要。现在,软弱意味着软弱,没有这样的惩罚。