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
^NSString *(NSString *title) { ... }is a block literal.- A
typedeftames the declaration for reuse. - Blocks assign to variables and call like functions.
Keywords and builtins used here
NSStringintlongmainreturntypedefvoid
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.
Step 1 of 3 in Blocks, step 16 of 27 in Language basics.