In ARC enabled code, how to fix a warning about a potential retain cycle, when using a block-based API?
The warning:
Capturing 'request' strongly in this block is likely to lead to a retain cycle
produced by this snippet of code:
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:...
[request setCompletionBlock:^{
NSDictionary *jsonDictionary = [[CJSONDeserializer deserializer] deserialize:request.rawResponseData error:nil];
// ...
}];
Warning is linked to the use of the object request
inside the block.
what the difference between __weak and __block reference?
Replying to myself:
My understanding of the documentation says that using keyword
block
and setting the variable to nil after using it inside the block should be ok, but it still shows the warning.Update: got it to work with the keyword '_weak' instead of '_block', and using a temporary variable:
If you want to also target iOS 4, use
__unsafe_unretained
instead of__weak
. Same behavior, but the pointer stays dangling instead of being automatically set to nil when the object is destroyed.Take a look at the documentation on the Apple developer website : https://developer.apple.com/library/prerelease/ios/#documentation/General/Conceptual/ARCProgrammingGuide/Introduction.html#//apple_ref/doc/uid/TP40011029
There is a section about retain cycles at the bottom of the page.
It causes due to retaining the self in the block. Block will accessed from self, and self is referred in block. this will create a retain cycle.
Try solving this by create a weak refernce of
self
Some times the xcode compiler has problems for identifier the retain cycles, so if you are sure that you isn't retain the completionBlock you can put a compiler flag like this:
The issue occurs because you're assigning a block to request that has a strong reference to request in it. The block will automatically retain request, so the original request won't deallocate because of the cycle. Make sense?
It's just weird because you're tagging the request object with __block so it can refer to itself. You can fix this by creating a weak reference alongside it.