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开发者_JS百科 seems to be conceptually similar to anonymous functions in JavaScript. Is this correct?
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. ;-)
Yes. Blocks in Objective-C are closures.
精彩评论