NotificationCenter
#NSNotification #Notification
概要
NotificationCenter は、登録された Observer に情報をブロードキャストするディパッチメカニズム。実行中のアプリケーションは default の notification center を持っているが、特定のコンテキストのみを扱う notification center を新たに作成することもできる。Observer の登録時には、どの notification を受け取るかどうかも同時に定義する。NotificationCenter は単一のプログラム上でのみ動作する。もし他のプロセスとやりとりしたい場合は、DistributedNotificationCenter を代わりに利用する。
利用する
登録する
Swift では、通知の名前は NSNotification.Name のネスト型で定義されている。実際には String。obj には notification の送信元のオブジェクトを設定する。設定すると、設定したオブジェクトからの通知のみが届くようになる。nil にすると全ての通知が届く。
code:swift
func addObserver(forName name: NSNotification.Name?,
object obj: Any?,
queue: OperationQueue?,
using block: @escaping (Notification) -> Void) -> NSObjectProtocol
func removeObserver(_ observer: Any,
name aName: NSNotification.Name?,
object anObject: Any?)
addObserver(forName:object:queue:using:) - Apple Developer
removeObserver(_:name:object:) - Apple Developer
例えば、アプリがアクティブになった際には UIApplicationdidBecomeActiveNotification が呼ばれるが、それを監視するのは以下のように書ける。
code:swift
// selector を使う
center.addObserver(self,
selector: #selector(type(of: self).notified(notification:)),
name: .UIApplicationDidBecomeActive,
object: nil)
// クロージャを使う
center.addObserver(forName: .UIApplicationDidBecomeActive,
object: nil,
queue: nil) { _ in print("called") }
自身で通知名を定義する場合は以下のようにする。
code:swift
extension Notification.Name {
static let myNotification = Notification.Name("myNotification")
}
center.addObserver(self,
selector: #selector(type(of: self).notified(notification:)),
name: .myNotification,
object: nil)
// struct を使うことで名前空間をきる事ができる
extension Notification.Name {
struct Qiita {
static let myNotification = Notification.Name("qiita.myNotification")
}
}
通知する
code:swift
// 全てに通知
func post(_ notification: Notification)
// 特定の通知
// Object が Notification として通知される?
func post(name aName: NSNotification.Name,
object anObject: Any?,
userInfo aUserInfo: AnyHashable : Any? = nil)
参考
NotificationCenter - Apple Developer
Swift 3 以降の NotificationCenter の正しい使い方 - Qiita