If a function I called from inside a block references ‘self’, would that create a retain cycle?
__weak id weakSelf = self;
- (void)firstFunction
{
id strongSelf = weakSelf;
if (!strongSelf) return;
[anObject performBlock:^{
[strongSelf secondFunction];
}];
}
- (void)secondFunction
{
[self doSomeCrazyStuff];
self.counter++;
//etc.
}
I’m calling ‘self’ in ‘secondFunction’, do I need to pass my weak pointer into this function and use it instead?
Potentially.
A retain cycle is created by having a cycle of strong references, apart from the qualifier (i.e. weak, strong) on the variable the actual variables where those references come from is irrelevant. So
strongSelfreferenced by your block is a strong reference toselfand you have the same potential for a retain cycle as if you’d usedselfitself.Re: comment
Having your block maintain a weak reference is the standard approach to addressing this issue. If you use
weakSelfin your block then there is no strong reference, if by the time the block is calledweakSelfisnilthen the call[weakSelf secondFunction]will do nothing – you are allowed to messagenilin Objective-C. You won’t create a cycle, during the call of the block a strong copy of the reference may be created but this will go after the call to the block returns.