Why should we copy blocks rather than retain?
Asked Answered
D

2

4

I recently met a problem using blocks with Facebook's app switching. I needed to call a block after the Facebook login.

First my block was destroyed when the app switched back ('cause it was on the stack), so I decided to retain it. But that didn't work, and I messed with that problem :/. I found a solution on that blog and also here.

My question is simply : why copy works and retain does not ?

Demolition answered 4/2, 2013 at 9:25 Comment(0)
H
11

Because when you create a block there is nothing to retain, since it doesn't exist in the heap until you copy it there with Block_copy. This is covered in the WWDC lectures about blocks.

More info: http://www.friday.com/bbum/2009/08/29/blocks-tips-tricks/

Harold answered 4/2, 2013 at 9:29 Comment(5)
Ok! Thanks a lot that helps me to understand better how things work !Demolition
"However, as of iOS 6 they are treated as regular objects" They have always been treated as regular objects.Tiatiana
@Tiatiana What I meant was they are heap allocated objects. In iOS 5 they were stack objects that needed to be copied to the heap via block_copy (this is no longer needed)Harold
@borrrden: Not true. You always have to copy a block if you use it outside the scope where it was created.Tiatiana
@Tiatiana Ah, you are right. However, this is mostly handled for you by ARC which in effect makes block_copy a redundant exercise for most (all?) scenarios. This is what I was remembering.Harold
F
6

See my recent answer to another similar question:

By default blocks are created on the stack. Meaning they only exist in the scope they have been created in.
[...]
Read Stack and Heap Objects in Objective-C by Mike Ash for more info on stack vs. heap.

Freewheeling answered 4/2, 2013 at 9:37 Comment(1)
Thanks for your answer too, your link was useful!Demolition

© 2022 - 2024 — McMap. All rights reserved.