Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Protocols, Categories and Blocks

Blocks - Closures in Objective-C

Learn Objective-C blocks - the caret syntax, parameters and return types, typedefs, capturing variables, the __block modifier, copy semantics and using blocks as callbacks and completion handlers.

A block is Objective-C's closure: a piece of code you can store in a variable, pass to a method, return from a function, and run later, with access to the variables around it when it was created. Blocks are how modern Cocoa APIs take callbacks, sort comparators, enumeration bodies and completion handlers. If you have used lambdas in C++ or closures in Swift and JavaScript, the idea is familiar. The syntax is the part that takes getting used to.

Blocks are a C-level feature (Apple's extension to C, C++ and Objective-C), and in Objective-C they are objects: they can be copied, retained and stored in collections.

Syntax

A block literal starts with a caret ^:

OBJECTIVEC
void (^sayHello)(void) = ^{
    NSLog(@"Hello from a block");
};
sayHello();      // call it like a C function

int (^add)(int, int) = ^(int a, int b) {
    return a + b;
};
NSLog(@"%d", add(3, 4));   // 7

The variable declaration has the shape returnType (^name)(parameterTypes). The literal is ^returnType (parameters) { body }, where the return type may be omitted if the compiler can infer it.

Because those declarations are hard to read, use a typedef:

OBJECTIVEC
typedef void (^CompletionHandler)(BOOL success, NSError *error);
typedef NSComparisonResult (^Comparator)(id a, id b);

- (void)loadWithCompletion:(CompletionHandler)completion;

Blocks as arguments

Foundation is full of block-taking methods:

OBJECTIVEC
NSArray *numbers = @[@5, @2, @9, @1];

NSArray *sorted = [numbers sortedArrayUsingComparator:^NSComparisonResult(NSNumber *a, NSNumber *b) {
    return [a compare:b];
}];

[sorted enumerateObjectsUsingBlock:^(NSNumber *n, NSUInteger idx, BOOL *stop) {
    NSLog(@"%lu: %@", (unsigned long)idx, n);
    if (idx == 2) *stop = YES;   // stop early
}];
OBJECTIVEC
// your own API
- (void)fetchUserWithID:(NSInteger)ident
             completion:(void (^)(NSDictionary *user, NSError *error))completion {
    // ... do work ...
    if (completion) completion(user, nil);   // always check for NULL: calling a NULL block crashes
}

Capturing variables

A block can read the local variables that are in scope where it is written. At creation, the block captures a copy of their values:

OBJECTIVEC
int base = 10;
int (^addBase)(int) = ^(int x) { return x + base; };
base = 100;
NSLog(@"%d", addBase(1));   // 11, not 101: base was copied when the block was created

Captured variables are read-only inside the block. To modify one, mark it __block, which moves it to shared storage that both the outer scope and the block see:

OBJECTIVEC
__block int counter = 0;
void (^bump)(void) = ^{ counter++; };
bump(); bump();
NSLog(@"%d", counter);   // 2

Captured object pointers are retained by the block (under ARC) for as long as the block lives. That is why a block stored on self that uses self makes a cycle; see retain cycles.

A runnable model of a closure

C has no blocks, but a closure is just "a function pointer plus the captured values". The stand-in below builds that by hand: a Block struct carries the function and its captured environment, with a shared __block variable represented by a pointer.

C Stand-in: a closure as function plus captured environment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Blocks and memory

Blocks start life on the stack, which dies with the scope. To keep a block beyond the current scope (store it in a property, add it to an array, call it asynchronously) it must be copied to the heap. ARC does this automatically in most cases, but a block property should still use copy:

OBJECTIVEC
@property (nonatomic, copy) void (^onComplete)(void);   // copy, never strong/assign in MRC

Returning blocks and function factories

A method or function can build a block that remembers its configuration:

OBJECTIVEC
typedef int (^Multiplier)(int);

Multiplier makeMultiplier(int factor) {
    return ^(int x) { return x * factor; };   // captures factor
}

Multiplier triple = makeMultiplier(3);
NSLog(@"%d", triple(14));   // 42

A rebuild of that idea in C: a function that returns a struct holding the function pointer and factor.

C Stand-in: a block factory remembering its factor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Calling a block that is NULL or nil crashes. Check before invoking.
  • Expecting a captured variable to update after the block is created (it does not, unless __block).
  • Capturing self in a block that self stores (cycle).
  • Declaring a block property as strong/assign: use copy.
  • Forgetting that *stop = YES is how you break out of enumerateObjectsUsingBlock:.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the correct declaration of a block variable returning int and taking two ints?

    The shape is returnType (^name)(parameterTypes).
  2. 2. Given int x = 5; void (^b)(void) = ^{ NSLog(@"%d", x); }; x = 9; b();, what prints?

    The block captured the value 5 when it was created.
  3. 3. What does __block do to a local variable?

    A __block variable lives in storage shared by the scope and every block that uses it.
  4. 4. Which attribute should a block property use?

    copy moves the block to the heap so it survives beyond the creating scope.

Summary

  • A block is a closure written ^returnType (params) { ... } and declared returnType (^name)(params).
  • Use typedef to make block types readable.
  • Values are captured at creation; __block makes a variable shared and mutable.
  • Block properties use copy; beware retain cycles with self.

Next: Blocks and Grand Central Dispatch