最終更新:2012-09-25 (火) 01:33:26 (4231d)  

NSNotificationCenter
Top / NSNotificationCenter

不特定多数のオブジェクトに対してメッセージを送信する必要がある場合、通知(Notification)と呼ばれる仕組みを利用する

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html

メソッド

インスタンスの取得

通知の登録

  • addObserver:(id)notificationObserver - オブザーバ (普段はself)
  • selector:(SEL)notificationSelector - 受け取りたい関数のセレクタ
  • name:(NSString *)notificationName - 通知名(NSNotification) (nilを指定するとすべての通知)
  • object:(id)notificationSender - 送信元オブジェクト (nilを指定するとすべての送信元からの通知)
  • を指定して通知がおこなわれるように登録する。
    //オブジェクトの登録
    - (void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender
  • notificationNameにnilを指定するとすべてのオブジェクトが通知される
  • objectを指定すると、特定のオブジェクトが通知したノーティフィケーションだけを受け取ることができる
  • objectにnilを指定すると、notificationNameに合うすべてのノーティフィケーションが通知される

通知の発行

  • - (void)postNotification:(NSNotification *)notification
    - (void)postNotificationName:(NSString *)notificationName object:(id)notificationSender
    - (void)postNotificationName:(NSString *)notificationName object:(id)notificationSender userInfo:(NSDictionary *)userInfo

登録済みの通知要求を削除

  • //オブジェクトの削除
    - (void)removeObserver:(id)notificationObserver//全部
    - (void)removeObserver:(id)notificationObserver name:(NSString *)notificationName object:(id)notificationSender

サンプル

//セレクタで指定するメソッド
-(void)someMethod:(NSNotification*)notification
{
  NSLog(@"%@ is notified",[notification name]);
}

//起動時に通知の設定を行う
-(void)awakeFromNib{
  NSNotificationCenter* center;

  //取得
  center = [NSNotificationCenter defaultCenter];
  //セレクタに通知名を設定
  [center addObserver:self //通知先オブジェクト
    selector:@selector(someMethod:) //通知先メソッドのセレクタ
    name: TestNotification //通知の名前
    object:nil]

}
//TestNotificationというノーティフィケーションを通知
[[NotificationCenter defaultCenter]postNotificationName:@"TestNotification" object:self userInfo:nil];

関連