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];
}
}
__weak XYZBlockKeeper *weakSelfinstead. I am uncomfortable seeing the__weakon the right-hand side of the*(this might not make a difference, but try it out. If it does then I have a theory why). - borrrdenweakSelf->memberVariable = 123;- borrrden-Wreceiver-is-weakflag (available as the “Sending messages to __weak pointers” build setting). Also, it's more sensible to put__weakafter the star, because__weakapplies toweakSelf(in thatweakSelfwill be set to zero, while*weakSelfwill not be set to zero). Consider thattypedef XYZBlockKeeper *XYZBlockKeeperRef; XYZBlockKeeperRef __weak weakSelf;declares a weak reference, buttypedef __weak XYZBlockKeeper WeakXYZBlockKeeper; WeakXYZBlockKeeper *weakSelf;does not (and gets a warning that__weakdoesn't apply). - rob mayoff__weakon the right hand of the*is the correct way to write it. developer.apple.com/library/mac/#releasenotes/ObjectiveC/… Putting it anywhere else is wrong but tolerated. - newacct