参考 mixi-inc/iOSTraining 7.4 NSNotification、NSNotificationCenter を用いた通知
NotificationCenter Class Reference
Notification Programming Topics
3つ目の通知パターンは Notification、NotificationCenter を用いた通知です。
この通知パターンは NotificationCenter のシングルトンインスタンスによるブロードキャストな通知を実現することができます。
通知を実現するためには以下のステップが必要です
- 通知を受けたいインスタンスに対して NotificationCenter にオブザーバ登録
- 通知ハンドラーの実装
- NotificationCenter に通知を post
- オブザーバ登録の解除
NotificationCenter.default.addObserver(self, //[1]オブザーバとして登録
selector: #selector(type(of: self).recieveNotification(_:)), //[2]通知ハンドラーの指定
name: NSNotification.Name(rawValue: "pushNotificationTapped"), //[3] 通知名
object: nil) // [4] sender の指定
オブザーバオブジェクトを指定します。指定したオブジェクトに変化通知が届きます。
通知を受け取った際に指定したセレクタが呼び出されます。
指定の通知名の通知を受け取ることが可能。nil を設定するとすべてのオブジェクトから通知を受け取る。
指定のオブジェクトからのみ通知を受けたいときに指定。nil を設定するとすべてのオブジェクトから通知を受け取る。
通知ハンドラは Notification オブジェクトを受け取るようにします。
func recieveNotification(_ notification: Notification) {
// do something
}
通知登録とハンドラの実装を closure を使ったパターンでまとめることもできます。
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "pushNotificationTapped"),
object: nil, queue: OperationQueue.main) { notification in
// do something
}
通知を post する際に userInfo として任意のデータ(Dictionary)を指定することができます。通知の受取手は Notification の userInfo プロパティでこのデータにアクセスすることが可能です。
let dict = ["key" : "value"]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pushNotificationTapped"), object: self, userInfo: dict)
NotificationCenter.default.removeObserver(self)
tabBarController プロジェクトを作成し、下記の仕様を満たすプログラムを作成してください。
- firstViewController で ボタンを押すと任意の文字列を持った userInfo を用いて通知を post する
- secondViewController で通知を取得し、上記の任意の文字列をラベルにセットする
この解答はsamples/day3/sample3-4にあります。