Re: Fire-and-forget controllers with blocks
Re: Fire-and-forget controllers with blocks
- Subject: Re: Fire-and-forget controllers with blocks
- From: Ken Thomases <email@hidden>
- Date: Fri, 20 May 2011 20:16:50 -0500
On May 20, 2011, at 9:10 AM, Dave Zarzycki wrote:
> One could naively and wrongly "fix" this by decoupling the init method:
>
> controller = [[MyImportController alloc] init];
> // "controller" is now non-nil and safe to capture
> [controller setCleanupBlock: ^{ [controller release] }];
> [controller start];
>
> But because blocks automatically retain/release captured objects, the above code has actually just created a simple retain cycle and will never be freed (the controller retains the block and vice versa).
The retain cycle is only a problem if the cleanup block is only called on dealloc. If it's called when the controller is simply finished with its task, then it's fine. The controller should also release the block after it's invoked it, though.
Also, the original code could have qualified the controller variable with __block and that would also have fixed the issue with controller having been captured when nil. Note that this also prevents the block from retaining the controller just because it's referenced.
Regards,
Ken
_______________________________________________
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