Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing a __weak pointer is not allowed inside block

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];
    }
}
like image 349
Rose Perrone Avatar asked Jul 24 '13 02:07

Rose Perrone


1 Answers

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.
    }
}
like image 139
timothy lau Avatar answered Oct 12 '22 18:10

timothy lau