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
Tweet

More Decks by Greg Heo

Other Decks in Programming

Transcript

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

    object in collection) { // do something here } Fast enumeration
  2. BLOCK METHOD void (^myBlock)(id, NSUInteger, BOOL *) = ^(id obj,

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

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

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

    alloc/init overhead Memory allocation considerations