Search code examples
iosmemory-managementautomatic-ref-countingblockretain-cycle

Referring to weak self inside a nested block


Suppose I already create a weak self using

__weak typeof(self) weakSelf = self;
[self doABlockOperation:^{
        ...
}];

Inside that block, if I nest another block:

[weakSelf doAnotherBlockOperation:^{
    [weakSelf doSomething];
}

will it create a retain cycle? Do I need to create another weak reference to the weakSelf?

__weak typeof(self) weakerSelf = weakSelf;
[weakSelf doAnotherBlockOperation:^{
    [weakerSelf doSomething];
}

Solution

  • It depends.

    You only create a retain cycle if you actually store the block (because self points to the block, and block points to self). If you don't intend to store either of the blocks, using the strong reference to self is good enough --- block will be released first after it got executed, and then it will release it's pointer to self.

    In your particular example, unless you're performing more operations which are not shown, you don't need to create any weakerWeakerEvenWeakerSelfs.