日々精進

新しく学んだことを書き留めていきます

エキスパートObjectiveーCプログラミング 2

・Blockは循環参照になりやすいので注意。Block内からselfを参照する場合は__weakを使うこと。
例は以下。

- (void)method{
    id __weak weakSelf = self;
    blk_t blk = ^int (int count){
        NSLog(@"%p", weakSelf);
        return 0;
    };
}



・以下のコードはBlock内でselfを参照していないのに循環参照になる!!

typedef int (^blk_t)(int);

@implementation MyClass {
    id obj;
}

- (void)method{
    blk_t blk = ^int (int count){
        NSLog(@"%p", obj);
        return 0;
    };
}

理由はBlock内からインスタンス変数にアクセスする場合、裏でselfをキャプチャして、self->objのようにself経由でインスタンス変数にアクセスするため。
これも__weakを使うことで回避できる。

- (void)method{
    id __weak weakObj = obj;
    blk_t blk = ^int (int count){
        NSLog(@"%p", weakObj);
        return 0;
    };
}