Notification
Poster
とObserver
は直接繋がっていないが、addObserver
を使って、通知を監視し通知があった際に#selecter
で指定した関数を実行可能です。
import Foundation
class Poster {
static let notificationName = Notification.Name("SomeNotification")
func post(message: String) {
NotificationCenter.default.post(name: Poster.notificationName, object: message)
}
}
class Observer {
init() {
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: Poster.notificationName, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func handleNotification(_ notification: Notification) {
if let object = notification.object {
print(object)
}
print("通知を受け取りました")
}
}
var observer = Observer()
let poster = Poster()
poster.post(message: "Hello")