Apple docs say I can avoid a strong reference cycle by capturing a weak reference to self, like this:
- (void)configureBlock {
    XYZBlockKeeper * __weak weakSelf = self;
    self.block = ^{
        [weakSelf doSomething];   // capture the weak reference
                                  // to avoid the reference cycle
    }
}
Yet when I write this code, the compiler tells me:
Dereferencing a __weak pointer is not allowed due to possible null value caused by race condition, assign it to strong variable first
Yet doesn't the following code create a strong reference cycle, and possibly leak memory?
- (void)configureBlock {
    XYZBlockKeeper *strongSelf = self;
    self.block = ^{
        [strongSelf doSomething];
    }
}
                You should use like this one: eg:
__weak XYZBlockKeeper *weakSelf = self;
self.block = ^{
    XYZBlockKeeper *strongSelf = weakSelf;
    if (strongSelf) {
        [strongSelf doSomething];
    } else {
        // Bummer.  <self> dealloc before we could run this code.
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With