ios - How blocks handles __weak references -
from huge number of questions breaking retain cycles inside blocks, question following:
how block handles __weak
references inside of it?
i aware of (taken here):
blocks retain nsobject use enclosing scope when copied.
so how takes care of __weak
qualification ownership? in theory since __weak
won't retain it? keep reference it?
correct, weak references not retained. works precisely expect. set nil
once object deallocated.
while (you don't want retained mere existence of block), can problematic. want make sure once block beings executing, it's retained duration of execution of block (but not prior execution of block). that, can use weakself
/strongself
pattern:
__weak myclass *weakself = self; self.block = ^{ myclass *strongself = weakself; if (strongself) { // ok can bunch of stuff, using strongself // confident won't lose in middle of block, // not causing strong reference cycle (a.k.a. retain // cycle). } };
that way, won't have retain cycle, don't have worry getting exceptions or other problems can result if used weakself
alone.
this pattern illustrated in "non-trivial cycles" discussion in use lifetime qualifiers avoid strong reference cycles in transitioning arc release notes david referenced.
Comments
Post a Comment