我可以通过传入 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
之外的对象的方法注册为回调?
最佳答案
这与“另一个类”无关。它与对象的生命周期有关。
你是说let observer = Another()
在下一个瞬间,方法 didFinish
结束,您的 Another 实例 observer
,化作一缕青烟消失。所以通知中心没有人可以与之交谈。任何通知都没有机会到达;观察者在这一切发生之前就已经消失了。
(事实上,过去这样做会崩溃,因为您离开通知中心时留下了一个“悬空指针”。现在您不会崩溃,但什么也没有发生。)
self
的情况并非如此,不是因为self
是“同一个类”,但因为它是应用程序委托(delegate),它在应用程序的整个生命周期中都存在。
关于cocoa - swift 5.1/ cocoa : How do I register a method in a class other than self as a notification observer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60066857/