9/12/2011

NSNotificationCenterのサンプルSnippet

登録、通知、監視、登録解除の流れをごく簡単に列挙。

登録
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(valueChanged:) name:@"ValueChanged" object:nil];

通知
NSString *value = @"Value";
NSNotification *n = [NSNotification notificationWithName:@"ValueChanged" object:value];
[[NSNotificationCenter defaultCenter]postNotification:n];

監視
※事前に登録をしておいた上でselectorのメソッドを実装する。
- (void)valueChanged:(NSNotification *)n{
NSString *str = n.object;
NSLog(@"%@",str);
}

登録削除
- (void)viewDidUnload
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [super viewDidUnload];
}

0 件のコメント:

コメントを投稿