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
__block NSInteger runglets the block mutate the variable.- Each call through
ringUpupdates the shared storage. - A plain capture like
clerkis frozen at definition time.
Keywords and builtins used here
NSString__blockintlongmainreturnvoid
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.
Step 2 of 3 in Blocks, step 17 of 27 in Language basics.