iOSアプリ開発においてデリゲートを自作する方法

デリゲートは委譲とも呼ばれ、あるオブジェクトの処理の一部を、別のオブジェクトに処理させることを指す。
Appleから提供されているライブラリにも、この仕組みは多用されているので、開発中に使用する機会は多い。
今回は、このデリゲートの仕組みを自作する方法を紹介する。

<手順>
1.「.h」ファイルに「@protocol」を使用してデリゲートを定義する
2.「.h」ファイルにデリゲートメソッドを定義する
3.「.h」ファイル「delegate」プロパティを定義する
4.「.m」ファイルに「@synthesize delegate」を記述する
5.「.m」ファイルのメソッドから「デリゲートメソッド」を呼び出す

上記の手順を盛り込んだサンプルコードを下記に示す。

<サンプルコード>
Sample.h

#import <Foundation/Foundation.h>

@protocol SampleDelegate <NSObject>
  //↑↑↑ 手順1.「.h」ファイルに「@protocol」を使用してデリゲートを定義する

- (void) finishProcessWithStatus:(NSString *)status;
  //↑↑↑ 手順2.「.h」ファイルにデリゲートメソッドを定義する

@end

@interface Sample : NSObject

@property (nonatomic, retain) id<SampleDelegate> delegate;
  //↑↑↑ 手順3.「.h」ファイル「delegate」プロパティを定義する

- (void) startProcess;

@end

Sample.m

#import "Sample.h"

@implementation Sample

@synthesize delegate;
  //↑↑↑ 手順4.「.m」ファイルに「@synthesize delegate」を記述する

- (void) startProcess{
    
    NSLog(@"Sample#startProcess 実行開始");
    
    [self.delegate finishProcessWithStatus:@"success"];
	//↑↑↑ 手順5.「.m」ファイルのメソッドから「デリゲートメソッド」を呼び出す

    NSLog(@"Sample#startProcess 実行終了");
}

@end

上記Sampleクラスの使用例を下記に示す。

<使用側サンプルコード>

#import "Caller.h"
#import "Sample.h"

@implementation Caller

- (void) callProcess{
    
    Sample *sample = [[Sample alloc] init];
    sample.delegate = self;  //デリゲート先を自身に設定している
    
    [sample startProcess];
}

//デリゲートメソッドを実装する
- (void) finishProcessWithStatus:(NSString *)status{
      
    NSLog(@"finishProcessWithStatus実行 status:%@",status);
}

@end

<実行結果>

2014-11-17 20:08:59.742 DelegateSample[10166:63385] Sample#startProcess 実行開始
2014-11-17 20:08:59.743 DelegateSample[10166:63385] finishProcessWithStatus実行 status:success
2014-11-17 20:08:59.743 DelegateSample[10166:63385] Sample#startProcess 実行終了

<考察>
ログの出力順序を注視すると、「Sample#startProcess」の実行途中に、「Caller」クラスに定義した「finishProcessWithStatus」メソッドが実行されていることが分かる。
「Caller#finishProcessWithStatus」実行完了後に、再び「Sample#startProcess」制御が戻っている事も確認できる。
この仕組みを上手く利用すると、汎用性の高いクラスを作成することができ、開発効率の向上につながる。

Enjoy Programing!!

<お勧め書籍>

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