[iPhone] Objective- Cの勉強メモ:NSNotificationCenterでイベント通知の管理
Objective-CはASと違ってデリゲートとという機能がある。
デリゲートとは別に色んなクラスが通知するイベントを一括で管理してくれるクラスがあるみたい。
それが、NSNotificationCenterクラス。
手順としては、
1.NSNotificationCenterのインスタンスを生成
2.通知の登録(インスタンスに通知先、リスナー関数、通知の種類、通知の送信元)
3.通知の開始
4.(通知の終了)
5:(通知の登録解除)
例)
//playerはMPMusicPlayerControllerのインスタンス //通知センタのインスタンを取得 NSNotificationCenter* noteCenter = [NSNotificationCenter defaultCenter]; //addObserver:通知先 //selector:リスナー関数 //name:通知してほしい通知の種類? //object:通知の送信元 [noteCenter addObserver:self selector:@selector(hoge:) name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:player]; //通知開始を指示 [player beginGeneratingPlaybackNotifications];
nameはnilにすると全ての種類のイベントが取得対象になる。
(そもそも通知の送信元がどのようなイベントを発信してるかを把握してる必要あり?)
(ドキュメントみれば書いてあるのかな?)
objectはnilにすると、全ての送信元からイベントを受け取る。
あとNSNotificationCenterはシングルトンになるので、インスタンス変数の保持はしなくてもいいみたい。
Tweet