As you probably have heard or read iPhone OS 4 (iOS4) some methods now accept blocks(Block objects). But how do you actually use them and how do they work? In this tutorial I try to explain how blocks can be used, what they do and how you can use them in your own (class) methods.
What are blocks?
You might know blocks as Closures, Lambdas or Procs from other languages and in Objective-C they act the same. Blocks or Block Objects are similar to — but far more powerful than — traditional function pointers. The differences are:
- Blocks are “anonymous functions” and can be defined inline.
- Blocks capture read-only copies (unless defined with __block, more on that later) of local variables, similar to “closures” in other languages.
Blocks are actually not “Objective-C” only, they can be used in regular C as well in C++.