cocoa - swift 5.1/ cocoa : How do I register a method in a class other than self as a notification observer?

标签 cocoa swift5

我可以通过传入 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/

相关文章:

ios - 无法使用 SwiftUI 加载相机

macos - 如何使用 swift 5 处理 NSComboBox 中的退格键

ios - 如何使用字体修改器? SwiftUI 中的大写和字体大小

objective-c - 使用 Objective-C/Cocoa 以 root 身份运行 Bash 脚本

iphone - 为什么我似乎无法在 iPhone 应用程序中取消归档由 OS X 应用程序归档的对象?

cocoa - EDMessage.framework错误

ios - 使用 .gesture(LongPressGesture) 打破 Scrollview

cocoa - 为什么 Sierra 要求联系人 (AddressBook) 权限?

objective-c - 用另一个 View 替换 View 时保持约束

ios - viewmodifier : puzzled about how the application is different for . shadow() 和 .font 中的 Swift body 方法