iOSアプリ開発におけるNotification(通知)の使い方

Notification(通知)は、任意のオブジェクトに対して、メッセージを通知する仕組みである。
今回はNotification(通知)の使い方を紹介する。

<注意>
Notification(通知)は非常に便利な仕組みであるが、多用するとソースコードの可読性を損なう恐れがある。
特に複数人で開発を行う場合は、使用場面を制限するなどの規約を設けた方が良いと思われる。

<使用方法概要>
Notification(通知)をオブジェクトが受け取るには、どんな通知を受け取りたいかを「NSNotificationCenter」に登録する必要がある。
登録には「NSNotificationCenter」クラスの「addObserver: selector: name: object:」メソッドを使用する。

一方、Notification(通知)を発行するには、「NSNotificationCenter」クラスの「postNotification:」メソッドを使用する。

以下にNotification(通知)のサンプルコードを示す。

<サンプルコード>
通知の受取手

#import "Caller.h"

#import "Sample.h"

@implementation Caller
    
- (void) callLogic{
    
    //NSNotificationCenterを取得する
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    
    //NSNotificationCenterへ登録する
    [nc addObserver:self                        //このクラスの
           selector:@selector(notifiListener:)  //notifiListenerというメソッドに
               name:@"NOTIFI_NAME"              //「NOTIFI_NAME」という名前の通知を知らせて
             object:nil];
    
    //Notification(通知)を発行する処理を呼び出す
    Sample *sample = [[Sample alloc] init];
    [sample startLogic];
}

//通知を受け取るメソッド
- (void) notifiListener:(NSNotification *)notifi{
    
    //NSNotificationCenterを取得する
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    
    //NSNotificationCenterへの登録を削除する
    [nc removeObserver:self];
    
    NSLog(@"Notificationにより通知された値\n%@", notifi.userInfo);
}

@end

通知の発行側

#import "Sample.h"

@implementation Sample

- (void) startLogic{
    
    //通知先に連携する情報をDictionaryとして準備する
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:@"success" forKey:@"result"];
    [dic setObject:@"0000001" forKey:@"status"];
    
    //発行するNSNotificationを作成する
    NSNotification *notifi =
    [NSNotification notificationWithName:@"NOTIFI_NAME"  //「NOTIFI_NAME」という名前の通知を
                                  object:self
                                userInfo:dic];           // dicに詰め込んだ情報と共に作成する
    
    //Notification(通知)を発行する
    [[NSNotificationCenter defaultCenter] postNotification:notifi];
}

@end

<実行結果>

2014-11-18 20:14:28.342 NotificationSample[18432:97413] Notificationにより通知された値
{
    result = success;
    status = 0000001;
}

Enjoy Programing!!

<お勧め書籍>

詳解 Objective-C 2.0 第3版
iOSアプリ開発技術者として仕事をするのであれば、必ず読んでおくべき書籍である。
筆者も何度も繰り返し精読している。