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 ?

Community
  • 1
  • 1
Jeremy
  • 248
  • 4
  • 12

2 Answers2

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/

iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
borrrden
  • 33,256
  • 8
  • 74
  • 109
  • Ok! Thanks a lot that helps me to understand better how things work ! – Jeremy Feb 04 '13 at 09:44
  • "However, as of iOS 6 they are treated as regular objects" They have always been treated as regular objects. – newacct Oct 17 '14 at 19:42
  • @newacct 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) – borrrden Oct 18 '14 at 03:20
  • @borrrden: Not true. You always have to copy a block if you use it outside the scope where it was created. – newacct Oct 18 '14 at 06:47
  • @newacct 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. – borrrden Oct 19 '14 at 07:13
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.

Community
  • 1
  • 1
Joris Kluivers
  • 11,894
  • 2
  • 48
  • 47