typestar

Blocks in Objective-C

Function values with the famous inside-out type spelling.

#import <Foundation/Foundation.h>

// A typedef tames the block type's inside-out spelling.
typedef NSString *(^Labeler)(NSString *);

int main(void) {
    @autoreleasepool {
        // ^ opens a block literal: a function value with a body.
        Labeler tag = ^NSString *(NSString *title) {
            return [NSString stringWithFormat:@"[USED] %@", title];
        };
        NSLog(@"%@", tag(@"Court and Spark"));

        NSInteger (^discount)(NSInteger) = ^NSInteger(NSInteger cents) {
            return cents * 80 / 100;
        };
        NSLog(@"Sale price: %ld", (long)discount(2499));
    }
    return 0;
}

How it works

  1. ^NSString *(NSString *title) { ... } is a block literal.
  2. A typedef tames the declaration for reuse.
  3. Blocks assign to variables and call like functions.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
528
Tokens
111
Three-star pace
60 tpm

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

Type this snippet

Step 1 of 3 in Blocks, step 16 of 27 in Language basics.

← Previous Next →

Blocks in other languages