Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Objective-C blocks similar to anonymous functions in JavaScript?

I'm trying to understand the concept of blocks. What I've read so far seems to be conceptually similar to anonymous functions in JavaScript. Is this correct?

like image 236
Florian Grell Avatar asked Sep 16 '10 09:09

Florian Grell


2 Answers

Yes, for the largest part. Blocks are kind-of C functions treated kind-of like objects which can capture variables from the surrounding scope. Anonymous functions are equivalent to blocks, but certainly not identical due to the rather complicated behind-the-scene machinery of blocks.

For example, if you plan to use a block after/outside the function/method which defines the block isn't active anymore—it's the case if you set the block as a property somewhere or use in GCD (a multi-core operation queueing library), you need to copy it with Block_copy() (or [aBlock copy]). I won't go into the details, but this is certainly not something you do with JS (anonymous) functions. It has to do with the fact that block literals are allocated on the stack (and not somewhere in the code) and you need to copy it to the heap if you want it to persist.

It can get quite complicated (but rather beautiful in its design), but for most use cases it's rather easy and you can treat it like anonymous JS functions. ;-)

like image 99
Constantino Tsarouhas Avatar answered Sep 23 '22 15:09

Constantino Tsarouhas


Yes. Blocks in Objective-C are closures.

like image 26
Georg Schölly Avatar answered Sep 25 '22 15:09

Georg Schölly