Я могу установить sh обратный вызов наблюдателя, передав 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
, в качестве обратного вызова?