■通知の受信側オブジェクトには通知センタへの登録と、通知の受信の2つが必要。
recieve.h
@class NSNotification;
- (void) setDone:(NSNotification *)aNotification;
- (void) setCancel:(NSNotification *)aNotification;
通知の受信メソッドの定義をする。
recieve.m
#import "recieve.h"
- (void)viewDidLoad
{
// 通知センタ登録
NSNotificationCenter* center;
center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(setDone:)
name:@"setDoneNotification" object:nil];
[center addObserver:self selector:@selector(setCancel:)
name:@"setCancelNotification" object:nil];
}
- (void) setDone:(NSNotification *)aNotification;
{
// 通知の送信側オブジェクト(send.m)でポストしたuserInfoは、[aNotification userInfo]で取得することができる。
NSLog(@"userInfo=%@", [aNotification userInfo]);
// Picker未選択の場合、NSDictionatyであるuserInfoの各項目には"(null)"がセットされるので、適宜処理すること。
if ([[[aNotification userInfo] objectForKey:@"hoge"] isEqualToString:@"(null)"]) {
// "(null)"の場合の処理
} else {
// "(null)"以外の場合の処理
}
}
- (void) setCancel:(NSNotification *)aNotification;
{
}
■通知の送信(ポスト)側オブジェクトでは、送信メソッドの定義をする。
send.h
@class NSNotification;
- (IBAction)doneButton:(id)sender;
- (IBAction)cancelButton:(id)sender;
send.m
#import "send.h"
- (IBAction)doneButton:(id)sender
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"setDoneNotification" object:self userInfo:pickerData];
}
- (IBAction)cancelButton:(id)sender
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"setCancelNotification" object:self];
}
オブザーバ、オブジェクト、セレクタ、通知名の名称は、送信側、受信側で合わせること。
タグ:iPhone