typestar

Block capture in Objective-C

Plain captures are snapshots; __block grants write access.

#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        // Blocks capture by value unless __block grants write access.
        __block NSInteger rung = 0;
        void (^ringUp)(NSInteger) = ^(NSInteger cents) {
            rung += cents;
        };

        ringUp(2499); ringUp(1250);
        NSLog(@"Till holds %ld cents", (long)rung);
        // A plain capture is a snapshot from definition time.
        NSString *clerk = @"Rae";
        void (^stamp)(void) = ^{ NSLog(@"Rung up by %@", clerk); };
        stamp();
    }
    return 0;
}

How it works

  1. __block NSInteger rung lets the block mutate the variable.
  2. Each call through ringUp updates the shared storage.
  3. A plain capture like clerk is frozen at definition time.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
465
Tokens
103
Three-star pace
65 tpm

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

Type this snippet

Step 2 of 3 in Blocks, step 17 of 27 in Language basics.

← Previous Next →