15

Apple のドキュメントによると、次のように自己への弱い参照をキャプチャすることで、強い参照サイクルを回避できるとのことです。

- (void)configureBlock {
    XYZBlockKeeper * __weak weakSelf = self;
    self.block = ^{
        [weakSelf doSomething];   // capture the weak reference
                                  // to avoid the reference cycle
    }
}

しかし、このコードを書くと、コンパイラーは次のように教えてくれます。

競合状態によって null 値が発生する可能性があるため、__weak ポインターの逆参照は許可されません。最初にそれを強い変数に割り当てます

しかし、次のコードは強力な参照サイクルを作成し、メモリ リークを引き起こす可能性はありませんか?

- (void)configureBlock {
    XYZBlockKeeper *strongSelf = self;
    self.block = ^{
        [strongSelf doSomething];
    }
}
4

1 に答える 1

27

次のように使用する必要があります。

__weak XYZBlockKeeper *weakSelf = self;

self.block = ^{

    XYZBlockKeeper *strongSelf = weakSelf;

    if (strongSelf) {
        [strongSelf doSomething];
    } else {
        // Bummer.  <self> dealloc before we could run this code.
    }
}
于 2013-07-24T03:21:20.377 に答える