LoginSignup
1
0

More than 5 years have passed since last update.

blockを使ったコールバック

Posted at

Objective-cのコールバック処理に関して、普段からデリゲートばかり使っていたので、今回初めてblockを使って、コールバック処理を行ってみました。
最低限の処理しかしていないですが、備忘録として残します。

今回は、処理の完了後にコールバックでテキスト型の値を受け取り、出力しています。

必要となるhandlerの定義

OtherClass.h
typedef void (^CallbackHandler)(NSString *returnText);

@interface OtherClass : NSObject

-(void)doSomeWorkWith:(CallbackHandler)handler;

@end
OtherClass.m
#import "OtherClass.h"

@interface OtherClass ()

@end

@implementation OtherClass

-(void)doSomeWorkWith:(CallbackHandler)handler {

    // 何らかの処理を行います。

    // 処理結果を用意
    NSString *returnText = @"処理結果テキスト";

    // コールバックが指定されている場合には、それを呼び出す。
    if (handler) {
        handler(returnText);
    }
}

@end

実行結果

ボタンを押下することで”処理結果テキスト”が出力されるようにします。

ViewController.m
#import "ViewController.h"
#import "OtherClass.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)call {
    OtherClass *otherClass = [OtherClass new];

    [otherClass doSomeWorkWith:^(NSString *returnText) {

    // OtherClassのdoSomeWorkWithメソッド完了後、受け取った結果を出力
        NSLog(@"%@", returnText);
    }];
}

- (IBAction)blockTest:(id)sender {
    [self call];
}

@end 

まとめ

今回は、そのほかの処理を入れませんでしたが、非同期処理、並列処理の際は必要となると思いますので、
より実用的な形で使えるよう勉強を続けたいと思います。
加えて、デリゲート比べて、簡単に書けるため、用途に応じて使い分けたいと思います。

1
0
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
1
0