2014-01-29

Getting To Know "Blocks" in Objective-C

Blocks, also known as closures, are a programming/compiler trick to treat a chunk of code as on object. That chunk of code can be passed around, stored in collections, and executed now or later.

Apple has added full support for Blocks in recent releases of both Xcode versions 4 and 5. Apparently support for blocks was a major motivation for Apple to switch from the old GCC compiler technology to the modern LLVM/Clang world.

Blocks bring a new funky syntax. While truly grokking blocks may strain your brain, simply using them is not so difficult. Basically they replace some uses of Delegation and other callback techniques.

A new introduction and tutorial, Introduction to Objective-C Blocks, just appeared. This is the best written into on this topic that I've seen. The Wikipedia page on Blocks is also worth a look, as is the sibling page on Closure. Yet another good source of info is Part 2 of How to Use Blocks in iOS 5 Tutorial on the RayWenderlich.com site.