-
Notifications
You must be signed in to change notification settings - Fork 336
7.4 NSNotification、NSNotificationCenter を用いた通知
NSNotification Class Reference
NSNotificationCenter Class Reference
Notification Programming Topics
3つ目の通知パターンは NSNotification、NSNotificationCenter を用いた通知です。
この通知パターンは NSNotificationCenter のシングルトンインスタンスによるブロードキャストな通知を実現することができます。
通知を実現するためには以下のステップが必要です
- 通知を受けたいインスタンスに対して NSNotificationCenter にオブザーバ登録
- 通知ハンドラーの実装
- NSNotificationCenter に通知を post
- オブザーバ登録の解除
[[NSNotificationCenter defaultCenter] addObserver:self //[1]オブザーバとして登録
selector:@selector(recieveNotification:) //[2]通知ハンドラーの指定
name:@"notificationName" //[3] 通知名
object:nil]; // [4] sender の指定
オブザーバオブジェクトを指定します。指定したオブジェクトに変化通知が届きます。
通知を受け取った際に指定したセレクタが呼び出されます。
指定の通知名の通知を受け取ることが可能。nil を設定するとすべてのオブジェクトから通知を受け取る。
指定のオブジェクトからのみ通知を受けたいときに指定。nil を設定するとすべてのオブジェクトから通知を受け取る。
通知ハンドラは NSNotification オブジェクトを受け取るようにします。
-(void)recieveNotification:(NSNotification *)notification
{
// do something
}
通知登録とハンドラの実装を blocks を使ったパターンでまとめることもできます。
[[NSNotificationCenter defaultCenter] addObserverForName:@"notificationName"
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
// do something
}];
通知を post する際に userInfo として任意のデータ(NSDictionary)を指定することができます。通知の受取手は NSNotification の userInfo プロパティでこのデータにアクセスすることが可能です。
NSDictionary *dict = @{@"key":@"value"};
[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:self userInfo:dict];
[[NSNotificationCenter defaultCenter] removeObserver:self];
tabBarController プロジェクトを作成し、下記の仕様を満たすプログラムを作成してください。
- firstViewController で ボタンを押すと任意の文字列を持った userInfo を用いて通知を post する
- secondViewController で通知を取得し、上記の任意の文字列をラベルにセットする
はじめに
-
導入
-
1.3 UIViewController1 UIViewController のカスタマイズ(xib, autoresizing)
-
UIKit 1 - container, rotate-
-
UIKit 2- UIView -
-
UIKit 3 - table view -
-
UIKit 4 - image and text -
-
ネットワーク処理
-
ローカルキャッシュと通知
-
Blocks, GCD
-
設計とデザインパターン
-
開発ツール
-
テスト
-
In-App Purchase
-
付録