On Jan 26, 2012, at 6:04 PM, 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.
The solutions in ARC from best to worst are: 1. Use `__block` and set it to nil when you are done. This works fine for one-shot callbacks, for example. There is a temporary retain cycle but the cycle is broken by the assignment to nil. 2. Use `__block __weak`. The weak pointer breaks the retain cycle. 3. Use `__block __unsafe_unretained`. The unretained pointer breaks the retain cycle. This is more fragile than `__block __weak`, but may be necessary if you are deploying to iOS older than 5.0 or OS X older than 10.7. -- Greg Parker [email protected] Runtime Wrangler _______________________________________________ Cocoa-dev mailing list ([email protected]) 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 [email protected]
