Why has Apple designed block to be allocated on the stack unless copied? What's the benefit for such behavior? Why not just make it behave like a regular NSObject - alloc-init it and it goes on the heap automatically?
Asked
Active
Viewed 106 times
1 Answers
2
The reason why blocks are placed on the stack by default is speed. In the common case where the lifetime of the block is less than that of the stack function that contains it, this is a very good optimisation.
http://www.cocoawithlove.com/2009/10/how-blocks-are-implemented-and.html

Sulthan
- 128,090
- 22
- 218
- 270
-
You mean block for synchronous dispatch? – Boon May 09 '13 at 22:48
-
1@Boon that question doesn't make sense. – Sulthan May 09 '13 at 23:06
-
I meant to ask - what block will have lifetime shorter than the function that contains it, a block used by dispatch_sync? – Boon May 10 '13 at 15:15
-
@Boon The block on the stack has the same lifetime as any local stack variable. For example, if you create a block variable inside a `while` cycle, `for` cycle or inside an `if-else` branch, the life of the block ends when the local scope (e.g. the `while {}` scope) ends. – Sulthan May 10 '13 at 15:20
-
1@Boon: for example, a block that you use in `-enumerateObjectsWithOptions:usingBlock:` – user102008 May 11 '13 at 10:26