typestar

Blocks as parameters in Objective-C

Pass behavior into a function, C signature and all.

#import <Foundation/Foundation.h>

// A function that takes a block parameter, spelled in C style.
static void withEachSide(NSArray<NSString *> *sides,
                         void (^play)(NSString *side, BOOL last)) {
    NSUInteger n = [sides count];
    for (NSUInteger i = 0; i < n; i++) {
        play(sides[i], i == n - 1);
    }
}

int main(void) {
    @autoreleasepool {
        withEachSide(@[ @"Side A", @"Side B" ],
                     ^(NSString *side, BOOL last) {
            NSLog(@"Now playing %@%@", side, last ? @" (flip me)" : @"");
        });
    }
    return 0;
}

How it works

  1. void (^play)(NSString *, BOOL) types the block parameter.
  2. The function calls the block once per element with context.
  3. The caller supplies the body inline at the call site.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
481
Tokens
129
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 129 seconds.

Type this snippet

Step 3 of 3 in Blocks, step 18 of 27 in Language basics.

← Previous Next →