On Jan 26, 2012, at 10:45 PM, Roland King wrote:

> 
> 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).

I agree, but in the case I ran into, I passed more than one block to the 
object, which would then call one of them depending on the outcome of its 
operations. Since not every block would be called, those temporary retain 
cycles would last forever. I'm also using ARC and targeting iOS 4.3. If you're 
only setting one block and you know it's going to be called, setting it to nil 
ought to do the trick.

Jeff Kelley
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to