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
strongSelfvariable it keepsselfalive while block executes (i.e. while it's not executed and sits in a property there's no strong reference). When you referenceselfdirectly -selfis captured and retained, now it keepsselfwhile block is alive.See the difference? If you kill all strong pointers to object with direct
selfreference there is still one strong reference inside the block, the one which was captured and retained. At the same time localstrongSelfpointer only holds strong reference toselfwhile block is executed, so, ifselfwas already dead,weakSelfwould be nil andstrongSelfwill get nil value.