Re: ARC and blocks
Re: ARC and blocks
- Subject: Re: ARC and blocks
- From: Roland King <email@hidden>
- Date: Fri, 27 Jan 2012 11:45:50 +0800
On Jan 27, 2012, at 10:04 AM, Marco Tabini wrote:
> On 2012-01-26, at 6:09 PM, Jeff Kelley wrote:
>
>> Without ARC, you would use __block to prevent the block from retaining the object and causing the retain cycle. With ARC, however, the object is retained when you put it into the variable, so to avoid a retain cycle, you have to declare it like so:
>>
>> __unsafe_unretained __block MyViewController *myController = …
>>
>> It looks awful, yes, but without the first piece we were having extreme memory leaks.
>
> Maybe I'm reading this wrong, but I think this might be a bit too unsafe. If you declare something as __unsafe_unretained, ARC won't try to track the variable through its lifetime, so if for some reason that variable is deallocated and then your block gets called, your app will crash. The OP's code feels a bit safer to me: it retains the variable strongly, then Nils it at the end of the block to force a release. There's no retain cycle or memory leak, and the __block variable is guaranteed to stick around until your block is done with it.
>
Yes - that __unsafe_unretained pattern is in the transition guide, but it's not recommended and seems to be there more for illustration of what pre-ARC code was equivalent to. Just setting the __block variable nil will work fine under ARC and pre-ARC runtimes so, unless the code in that block is really complex and it's hard to set the block variable nil in all relevant places, I'd definitely use the OPs code (which is what the transition guide seems to recommend also).
_______________________________________________
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