u16suzuの blog

日々学んだことのメモブログです。

Block propertyを使用してエラー処理を共通化する

  • 実装ファイル
#import "ViewController.h"
#import "CustomView.h"

typedef void(^testBlockType)(void);

@interface ViewController ()
@property (nonatomic, copy) testBlockType success;
@property (nonatomic, copy) testBlockType failuer;
@end

@implementation ViewController

- (void)viewDidLoad{
    self.success = ^(void){
        NSLog(@"Do something.");
    };
    self.failuer = ^(void){
        NSLog(@"Do common error handling process and so on.");
    };    
   
    __weak typeof(self) weakSelf = self;
    [self hogeMethodSuccess:weakSelf.success withFailuer:weakSelf.failuer];
    [self hogeMethod2];
}

Blockを引数にとるメソッド(通信処理をするメソッドを想定) 引数の型にtypedef で宣言した Block type を使うと かなりすっきりする. 見比べるためにfailuer だけ typedef による Block typeを使用した

- (void)hogeMethodSuccess:(void (^)(void))success
              withFailuer:(testBlockType)failuer
{
    int r = arc4random() % 2; // random number. range is 0-1.
    if( r == 0 ){
        success();
    }else{
        failuer();
    }
}


- (void)hogeMethod2{
    __weak typeof(self) weakSelf = self;
    [self hogeMethodSuccess:weakSelf.success withFailuer:weakSelf.failuer];
}
@end