User Tools

Site Tools


This is an old revision of the document!


A block is a chunk of code encapsulated within a variable. It can be passed along as a method parameter or assigned as a class property. It can be executed at any point. Blocks can be passed arguments.

The main usefulness of blocks is the ability to provide reactive implementations to events that may occur asynchronously or in remote objects. Examples: handling asynchronous HTTP replies, reacting to the end of an animation, etc.

In other languages blocks are also known as closures.

Using Blocks

Blocks are always denoted by a caret (^). This section will only cover the use of blocks provided by other classes, not the creation of your own blocks.

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[[NSOperationQueue alloc] init]
                       completionHandler:^(NSURLResponse *resp, NSData *data, NSError *err) {
                           // Do something with the data
                           // Because this block "closes around" and captures the surround scope,
                           // you can use someOtherClass in this block if necessary.

In this example:

  1. the block is passed as a parameter to “completionHandler” as a block literal- it is defined “inline”
  2. The block takes three arguments, resp, data, and err

The same block reformatted for clarity:

[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:
                       ^(NSURLResponse *resp, NSData *data, NSError *err) {

Note the curly braces wrapping the code, followed the the square bracket closing the method call.

Blocks introduce a number of scope issues:

  1. Local and instance variables cannot be referred to in a block unless declared with the “__block” prefix
  2. Properties can be used using the “”
  3. “self” can be used in a block, but doing so captures self. This is potentially dangerous

Best practice is not to access local, instance, or public variables of a class within a block literal defined in that class.

ios-labs-s14/advanced-blocks.1393696307.txt.gz · Last modified: 2014/03/01 11:51 by mbarboi