Slide 1

Slide 1 text

OBJC BLOCKS Blocks, blocks, blocks!

Slide 2

Slide 2 text

WHO AM I? @gregheo Programmer, general nerd, on-call emergency presenter

Slide 3

Slide 3 text

USER EXPECTATIONS Performance, performance, performance! Fast startup Responsiveness Background processing

Slide 4

Slide 4 text

BLOCKS Part of the performance puzzle Modular Re-use GCD integration

Slide 5

Slide 5 text

BLOCKS Similar to: Closures Lambdas Anonymous functions

Slide 6

Slide 6 text

HELLO, WORLD ^{ NSLog(@"Hello, world!"); }; ^{ NSLog(@"Hello, world!"); }(); direct call!

Slide 7

Slide 7 text

HELLO, WORLD void (^myBlock)() = ^{ NSLog(@"Hello, world!"); }; myBlock();

Slide 8

Slide 8 text

SYNTAX int (*)(char); int (^)(NSString *); Function pointers, anyone?

Slide 9

Slide 9 text

THE STORY Some uses: Enumeration Map / reduce

Slide 10

Slide 10 text

CLASSIC METHODS Iterating over a collection: for loop? NSEnumerator?

Slide 11

Slide 11 text

MODERN METHOD NSArray *collection = [[NSArray alloc] ...]; for (id object in collection) { // do something here } Fast enumeration

Slide 12

Slide 12 text

BLOCK METHOD [myArray enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) { // do something }]; Inline block

Slide 13

Slide 13 text

BLOCK METHOD void (^myBlock)(id, NSUInteger, BOOL *) = ^(id obj, NSUInteger idx, BOOL *stop) { // do something }; [myArray enumerateObjectsUsingBlock:myBlock]; Pre-declared block

Slide 14

Slide 14 text

BLOCK METHOD void (^myBlock)(id, NSUInteger, BOOL *) = ^(id obj, NSUInteger idx, BOOL *stop) { // do something }; [myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:myBlock]; Concurrency!

Slide 15

Slide 15 text

BENCHMARKS Regular enumeration 3.5 seconds Block enumeration 5 seconds Concurrent block 2.5 seconds (millions of iterations on an iPad 2)

Slide 16

Slide 16 text

NO FREE LUNCH Blocks are not a cure-all! Variable closure alloc/init overhead Memory allocation considerations

Slide 17

Slide 17 text

FURTHER TOPICS NSOperation NSBlockOperation Grand Central Dispatch

Slide 18

Slide 18 text

Questions? Comments? Rebuttals? ^{ return; }();