why does it work when we pass the weak reference to a strong reference inside the block? If a local variable in a block is retained, this should add a retain to self
and thus create this bad retain cycle?
Here is the example :
__weak id weakSelf = self;
[self.operationQueue addOperationWithBlock:^{
NSNumber* result = findLargestMersennePrime();
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
MyClass* strongSelf = weakSelf;
strongSelf.textLabel.text = [result stringValue];
}];
}];
When you create or copy a block (it could be copied when you, for example, schedule it to gcd), referenced variables are captured (unless declared with __block specifier). Strong references are retained, weak references are not.
When you create local
strongSelf
variable it keepsself
alive while block executes (i.e. while it's not executed and sits in a property there's no strong reference). When you referenceself
directly -self
is captured and retained, now it keepsself
while block is alive.See the difference? If you kill all strong pointers to object with direct
self
reference there is still one strong reference inside the block, the one which was captured and retained. At the same time localstrongSelf
pointer only holds strong reference toself
while block is executed, so, ifself
was already dead,weakSelf
would be nil andstrongSelf
will get nil value.