LoginSignup
26
26

More than 5 years have passed since last update.

NSNotificationの使い方

Last updated at Posted at 2013-01-15

ある値が変更されたタイミングで、動かしたい処理がある場合に有効(キー値監視)

Notification.m
// NSNotificationCenterを作る
- (void)viewDidLoad {
    // 通知を管理するNSNotificationCenterを生成
    NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
    // centerに「identifier」という名前の通知が来たときに、「getPost:」を実行することを設定
    [center addObserver:self selector:@selector(getPost:) name:@"identifier" object:nil];
}

// 通知を送る
- (IBAction)sendNotification {
    // NSNotificationを作成する
    NSNotification* notification = [NSNotification notificationWithName:@"identifier" object:@"ここにgetPostで使いたいオブジェクトを指定できる"];
    // NSNotificationCenterを取得する
    NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
    // 通知を行う
    [center postNotification:notification];
}

// 通知を受け取って実行されるメソッド
- (void)getPost:(NSNotification*)notification {
    // 通知のときに渡したオブジェクトを使うことができる
    NSLog(@"%@", notification.object);
}
ここにgetPostで使いたいオブジェクトを指定できる

NSNotificationは、NSObjectクラスで実装されているので、どこでも使える。

26
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
26