TExcelTAD
Home › Objective-C › Blocks

Blocks

A block is a chunk of code you can store in a variable, pass to a method and call later: Objective-C's version of a closure or lambda. Blocks start with a caret ^. Foundation uses them for enumeration, sorting and filtering; Apple's frameworks use them for completion handlers and animations.

Block syntax

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        // A block taking no arguments and returning nothing
        void (^sayHello)(void) = ^{
            NSLog(@"Hello from a block");
        };
        sayHello();

        // A block taking two ints and returning an int
        int (^add)(int, int) = ^int(int a, int b) {
            return a + b;
        };
        NSLog(@"3 + 4 = %d", add(3, 4));

        // The return type can usually be left out: the compiler infers it
        NSString *(^shout)(NSString *) = ^(NSString *text) {
            return [[text uppercaseString] stringByAppendingString:@"!"];
        };
        NSLog(@"%@", shout(@"blocks are objects"));
    }
    return 0;
}
Hello from a block
3 + 4 = 7
BLOCKS ARE OBJECTS!

The declaration int (^add)(int, int) reads: "add is a pointer to a block (^) that takes (int, int) and returns int". It looks like a C function pointer with ^ in place of *.

typedef for readable block types

Block types get long quickly. A typedef gives them a name:

objc · try it yourself
#import <Foundation/Foundation.h>

typedef double (^Operation)(double, double);

double apply(Operation op, double x, double y) {
    return op(x, y);
}

int main(void) {
    @autoreleasepool {
        Operation multiply = ^(double a, double b) { return a * b; };
        Operation power = ^(double a, double b) { return pow(a, b); };

        NSDictionary *ops = @{@"*": multiply, @"^": power};   // blocks are objects
        NSLog(@"6 * 7 = %.0f", apply(ops[@"*"], 6, 7));
        NSLog(@"2 ^ 10 = %.0f", apply(ops[@"^"], 2, 10));

        // A block literal passed inline
        NSLog(@"9 - 4 = %.0f", apply(^(double a, double b) { return a - b; }, 9, 4));
    }
    return 0;
}
6 * 7 = 42
2 ^ 10 = 1024
9 - 4 = 5

Blocks are Objective-C objects, so they can be stored in arrays and dictionaries and in properties (declared copy).

Blocks as method parameters

In a method declaration the block type is written in parentheses, without a name after the caret:

objc · try it yourself
#import <Foundation/Foundation.h>

@interface Downloader : NSObject
- (void)fetchFile:(NSString *)name completion:(void (^)(NSString *contents, BOOL success))completion;
@end

@implementation Downloader
- (void)fetchFile:(NSString *)name completion:(void (^)(NSString *, BOOL))completion {
    // A real downloader would work asynchronously; here we answer at once
    if ([name hasSuffix:@".txt"]) {
        completion([NSString stringWithFormat:@"contents of %@", name], YES);
    } else {
        completion(nil, NO);
    }
}
@end

int main(void) {
    @autoreleasepool {
        Downloader *d = [Downloader new];
        for (NSString *file in @[@"notes.txt", @"photo.raw"]) {
            [d fetchFile:file completion:^(NSString *contents, BOOL success) {
                if (success) {
                    NSLog(@"got: %@", contents);
                } else {
                    NSLog(@"failed to fetch %@", file);
                }
            }];
        }
    }
    return 0;
}
got: contents of notes.txt
failed to fetch photo.raw

This completion handler pattern is everywhere in Apple APIs: you pass the code to run when the work is done. Notice that the block uses file, a variable from the surrounding loop: blocks capture the variables they use.

Blocks with Foundation

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray *temps = @[@18, @25, @31, @12, @27];

        NSIndexSet *hot = [temps indexesOfObjectsPassingTest:^BOOL(NSNumber *t, NSUInteger i, BOOL *stop) {
            return t.integerValue > 24;
        }];
        NSLog(@"%lu hot days", (unsigned long)hot.count);

        NSPredicate *mild = [NSPredicate predicateWithBlock:^BOOL(NSNumber *t, NSDictionary *bindings) {
            return t.integerValue >= 15 && t.integerValue <= 26;
        }];
        NSLog(@"mild: %@", [[temps filteredArrayUsingPredicate:mild] componentsJoinedByString:@" "]);

        // A tiny "map": build a new array by transforming each element
        NSMutableArray *fahrenheit = [NSMutableArray array];
        [temps enumerateObjectsUsingBlock:^(NSNumber *c, NSUInteger i, BOOL *stop) {
            [fahrenheit addObject:@(c.integerValue * 9 / 5 + 32)];
        }];
        NSLog(@"in F: %@", [fahrenheit componentsJoinedByString:@" "]);
    }
    return 0;
}
3 hot days
mild: 18 25
in F: 64 77 87 53 80

Calling a nil block crashes

Messages to nil are harmless, but calling a nil block dereferences a null pointer and crashes. Check optional blocks before calling them:

objc
if (completion) {
    completion(result, YES);
}

Syntax cheat sheet

Where Syntax
local variable ReturnType (^name)(Params) = ^ReturnType(Params) { … };
method parameter - (void)doIt:(ReturnType (^)(Params))name;
property @property (nonatomic, copy) ReturnType (^name)(Params);
typedef typedef ReturnType (^TypeName)(Params);
literal, no arguments ^{ … }

Tip: The site fuckingblocksyntax.com (or its polite twin goshdarnblocksyntax.com) exists because almost everyone forgets this syntax. Using a typedef is the best cure.

Test yourself

Which declares a block variable square taking an int and returning an int?

  1. int ^square(int)
  2. int (^square)(int)
  3. ^int square(int)
  4. block<int(int)> square

Which property attribute should a block property use?

  1. assign
  2. weak
  3. copy
  4. readonly

What happens if you call a block variable that is nil?

  1. Nothing
  2. It returns 0
  3. The program crashes
  4. An NSException is raised and can be caught