Blocks are a powerful language feature. However, they are underused and under-appreciated in Objective-C, especially compared to Ruby. My intent is to make blocks easy to understand and show many practical uses of blocks.
and executed when needed Also known as lambdas, closures, anonymous functions, first-class functions, higher-order functions Can be passed as a parameter, returned from a method/function, and stored in data structures Blocks make adding new features to a language easy
are in scope when the block is created Closure makes it possible to store a block indefinitely, then restore the context at will Objective-C objects are automatically retained/released C objects must be manually retained/released
retain loops Unlike regular Objective-C objects, blocks are created on the stack Be sure to call -copy if you need it to live beyond the current stack frame Make sure to de-stackify blocks before storing them in a data structure
Object A Object B Object C Block So, Object B wraps Object A’s block in a new completion block. Object B then calls Object C with the new completion block.
Object A Object B Object C Block Object A calls Object B and passes a completion block. So, Object B wraps Object A’s block in a new completion block. Object B then calls Object C with the new completion block.
Object A Object B Object C Block Object A and Object B need to know when Object C finishes. So, Object B wraps Object A’s block in a new completion block. Object B then calls Object C with the new completion block.
Object A Object B Object C Block So, Object B wraps Object A’s block in a new completion block. Object B then calls Object C with the new completion block.
Object A Object B Object C Block So, Object B wraps Object A’s block in a new completion block. Object B then calls Object C with the new completion block.
Object A Object B Object C Block So, Object B wraps Object A’s block in a new completion block. Object B then calls Object C with the new completion block.
blocks Blocks are not tied to a thread until they are executed Blocks can be queued up without blocking threads Threads can spend more time running and less time waiting