A block is simply a block of code that can be used as a method argument. You can create variables to hold blocks (which we are not going to cover today), or you can add blocks in-line with the calling method.

Blocks are useful for defining method callbacks (for example, handling the response of an HTTP request) and completion handlers (for example, waiting for an animation to complete before moving on). The advantage is that all the code pertaining to a particular operation is grouped together instead of spread out all over a class implementation.

A block starts with a caret ^, optionally followed by arguments in parentheses (...), followed by code wrapped in curly brackets {...}.

Local variables can be used inside blocks, but they are read-only.

If you want to set local variables, you need to mark them with the __block keyword.

Instance variables can be used inside blocks without any special flags.

  1. Paul Hegarty. Lecture 10 Slides. iPad and iPhone Application Development. Stanford, Nov 24 2011.

Comments are closed.