Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Intro to ObjC Blocks

Intro to ObjC Blocks

Blocks: a brief introduction to what they are and why you want to use them.

Slides are from a talk given for the Toronto Apple user group, July 2011.


Greg Heo

April 18, 2012

More Decks by Greg Heo

Other Decks in Programming


  1. OBJC BLOCKS Blocks, blocks, blocks!

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

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

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

  5. BLOCKS Similar to: Closures Lambdas Anonymous functions

  6. HELLO, WORLD ^{ NSLog(@"Hello, world!"); }; ^{ NSLog(@"Hello, world!"); }();

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

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

  9. THE STORY Some uses: Enumeration Map / reduce

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

  11. MODERN METHOD NSArray *collection = [[NSArray alloc] ...]; for (id

    object in collection) { // do something here } Fast enumeration
  12. BLOCK METHOD [myArray enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop)

    { // do something }]; Inline block
  13. BLOCK METHOD void (^myBlock)(id, NSUInteger, BOOL *) = ^(id obj,

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

    NSUInteger idx, BOOL *stop) { // do something }; [myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:myBlock]; Concurrency!
  15. BENCHMARKS Regular enumeration 3.5 seconds Block enumeration 5 seconds Concurrent

    block 2.5 seconds (millions of iterations on an iPad 2)
  16. NO FREE LUNCH Blocks are not a cure-all! Variable closure

    alloc/init overhead Memory allocation considerations
  17. FURTHER TOPICS NSOperation NSBlockOperation Grand Central Dispatch

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