Re: ARC and blocks
Re: ARC and blocks
- Subject: Re: ARC and blocks
- From: Conrad Shultz <email@hidden>
- Date: Thu, 26 Jan 2012 14:44:08 -0800
On 1/26/12 1:51 PM, Jan E. Schotsman wrote:
> Hello,
>
> This code is given in the "Transitioning to ARC Release Notes" as an
> example of accomodating blocks in an ARC environment:
>
> __block MyViewController *myController = [[MyViewController alloc] init…];
> // ...
> myController.completionHandler = ^(NSInteger result) {
> [myController dismissViewControllerAnimated:YES completion:nil];
> myController = nil;
> };
>
> Supposedly this avoids a retain cycle. But where is the cycle? At least
> two objects are needed for a cycle. What is the second one?
> Excuse me if I'm being dumb.
>
The block normally would retain variables it captures from its scope,
including, in this case, myController. Presumably myController would
retain the completionHandler block, ergo a retain cycle.
However, __block variables are NOT retained automatically by a block
during capture, so this breaks the retain cycle.
So, when myController is nil'ed out, ARC releases it, and it releases
the block in turn. No leaks/abandoned memory.
A special form of this is the idiom:
__block id mySelf = self;
^{
[mySelf doSomething];
}
This lets you use self in a block without retaining it.
--
Conrad Shultz
Synthetiq Solutions
www.synthetiqsolutions.com
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden