Pragmatic blocks

1,329 views

Published on

For the best viewing experience, please download this presentation and view it in Keynote. SlideShare doesn't handle the animations well.

Blocks are a powerful language feature. However, they are underused and under-appreciated in Objective-C, especially compared to Ruby. My intent is to make blocks easy to understand and show many practical uses of blocks.

Published in: Technology, Business
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,329
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
47
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • \n
  • The practical application of blocks is language independent.\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • ARC usually handles calling -copy for you.\nARC does not handle calling -copy before storing a block in a data structure.\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Continuations are powerful enough to build many features into a language. For example, you can add exceptions to a language using continuations. \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • I’m assuming the 2-core processor is not hyper-threaded.\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • The builder pattern is, in a way, the opposite of the template pattern. A template defines the main algorithm and the subroutines are added in via implementing virtual methods or blocks. The builder pattern defines the subroutines and the conductor method or block defines the main algorithm. \n
  • \n
  • Advantages: \nNo need to subclass UITableView (RBTableView technically).\nEasy to make custom table views.\n
  • \n
  • \n
  • \n
  • \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • “Manager” does not imply the singleton pattern. The shared data manager could be any arbitrary object. \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Pragmatic blocks

    1. 1. Pragmatic Blocksby Robert Brown@robby_brown
    2. 2. ObjectivesIntroduce the concepts behind blocksTouch lightly on Objective-C syntaxFocus on practical applications of blocks
    3. 3. Introduction
    4. 4. What are blocks?Pieces of code that can be stored and executed whenneededAlso known as lambdas, closures, anonymousfunctions, first-class functions, higher-order functionsCan be passed as a parameter, returned from amethod/function, and stored in data structuresBlocks make adding new features to a language easy
    5. 5. What does “closure” mean?Blocks store all the variables that are in scope when theblock is createdClosure makes it possible to store a block indefinitely,then restore the context at willObjective-C objects are automatically retained/releasedC objects must be manually retained/released
    6. 6. Block SyntaxDeclaration Syntax:returnType (^blockName) (Arguments)Definition Syntax:^ returnType (Arguments) { code; }The return type and arguments are optional.
    7. 7. Block SyntaxExample: returnType (^block)(args) = ^(args) { ... };Block types are ugly, use typedef: typedef returnType (^MyBlock)(args); MyBlock block = ^(args) { ... };
    8. 8. GotchasRetain loops Xcode profiler will warn you of block retain loopsUnlike regular Objective-C objects, blocks are createdon the stack Be sure to call -copy if you need it to live beyond the current stack frame Make sure to de-stackify blocks before storing them in a data structure
    9. 9. Application
    10. 10. What are blocks good for?Completion callbacksContinuationsMultithreadingDelegate replacementOther design pattern modifications
    11. 11. CallbacksMost uses of blocks are some form of callbackSince blocks have closure, they can restore the caller’scontext without any effort on our part
    12. 12. Completion BlocksMost common use of blocks in Objective-CA callback that happens only after some task hasfinished Some operations, such as network requests take an unknown amount of time Core Animation also uses many completion blocks
    13. 13. Completion Blocks Object Object A B Block Object B finishes executing and calls Object A calls Object B and passescompletion block. the a completion block.
    14. 14. Completion Blocks Object Object A B Block Object B finishes executing and calls Object A calls Object B and passescompletion block. the a completion block.
    15. 15. Completion Blocks Object Object A B Block Object B finishes executing and calls Object A calls Object B and passescompletion block. the a completion block.
    16. 16. ContinuationsThink of it like a completion block wrapped in acompletion block wrapped in a completion block...Essentially building your own runtime stack.
    17. 17. Continuations Object Object Object A B C Block Object C BAthen calls Objectand to Object finisheswraps Object A’s Object A calls Object needwith So, Object B Object B B and calls Object and executing C block theacompletion C finishes. knownew completion block. passes new completion block. theinwhen Object block. a completion block.
    18. 18. Continuations Object Object Object A B C Block Object C BAthen calls Objectand to Object finisheswraps Object A’s Object A calls Object needwith So, Object B Object B B and calls Object and executing C block theacompletion C finishes. knownew completion block. passes new completion block. theinwhen Object block. a completion block.
    19. 19. Continuations Object Object Object A B C Block Object C BAthen calls Objectand to Object finisheswraps Object A’s Object A calls Object needwith So, Object B Object B B and calls Object and executing C block theacompletion C finishes. knownew completion block. passes new completion block. theinwhen Object block. a completion block.
    20. 20. Continuations Object Object Object A B C Block Object C BAthen calls Objectand to Object finisheswraps Object A’s Object A calls Object needwith So, Object B Object B B and calls Object and executing C block theacompletion C finishes. knownew completion block. passes new completion block. theinwhen Object block. a completion block.
    21. 21. Continuations Object Object Object A B C Block Object C BAthen calls Objectand to Object finisheswraps Object A’s Object A calls Object needwith So, Object B Object B B and calls Object and executing C block theacompletion C finishes. knownew completion block. passes new completion block. theinwhen Object block. a completion block.
    22. 22. Continuations Object Object Object A B C Block Object C BAthen calls Objectand to Object finisheswraps Object A’s Object A calls Object needwith So, Object B Object B B and calls Object and executing C block theacompletion C finishes. knownew completion block. passes new completion block. theinwhen Object block. a completion block.
    23. 23. Multithreading: GCDGrand Central Dispatch (GCD) makes heavy use ofblocksBlocks are not tied to a thread until they are executedBlocks can be queued up without blocking threadsThreads can spend more time running and less timewaiting
    24. 24. Multithreading: GCDCode can be made asynchronous simply bysurrounding it with dispatch_async(queue, ^{ ... });
    25. 25. Multithreading: GCDThread Pool Concurrent Queue Block Thread C D B A 3 2-Core Processor Thread 2 Thread 1
    26. 26. Multithreading: GCDThread Pool Concurrent Queue Block Thread C D 3 2-Core Processor Thread 2 Block B Thread Block 1 A
    27. 27. Multithreading: GCDThread Pool Concurrent Queue Block C D 2-Core Processor Thread Thread Block 3 1 A Thread Block 2 B
    28. 28. Multithreading: GCDThread Pool Concurrent Queue Block C D 2-Core Processor Thread Block 1 A Thread Thread Block 3 2 B
    29. 29. Multithreading: GCDThread Pool Concurrent Queue 2-Core Processor Thread Block 1 A Block D Thread Thread Block Block 3 2 B C
    30. 30. Multithreading: GCDThread Pool Concurrent Queue 2-Core Processor Thread Thread Block 2 1 A Block D Thread Block Block 3 B C
    31. 31. Multithreading: GCDThread Pool Concurrent Queue 2-Core Processor Thread Block 1 A Thread Thread Block Block 2 3 C B D
    32. 32. Multithreading: GCDThread Pool Concurrent Queue 2-Core Processor Thread Block 1 A Thread Thread Block Block 2 3 C B D
    33. 33. Multithreading: GCDThread Pool Concurrent Queue 2-Core Processor Thread Block 2 A D Thread Thread Block 1 3 C B
    34. 34. Multithreading: GCDThread Pool Concurrent Queue 2-Core Processor Thread Thread Block 3 2 A D Thread Block 1 C B
    35. 35. Multithreading: GCDThread Pool Concurrent Queue Thread 2 2-Core Processor Thread Block 3 A D Thread Block 1 C B
    36. 36. Block DelegationDelegates are essentially protocols that specify a list ofmethod callbacksThese method callbacks can be easily replaced withblock callbacksRule of thumb: 3 or less delegate callbacks should behandled using blocks.
    37. 37. Block DelegationAdvantages: No additional protocols No need to conform to a protocol Easy to change block callbacks dynamically
    38. 38. Block DelegationDisadvantages: May not be appropriate when more than 3 callbacks are needed
    39. 39. Other Design Patterns
    40. 40. Template MethodSometimes algorithms differ by only a few linesThose few lines can be replaced by a virtual methodSubclasses define the virtual method
    41. 41. Template MethodLet’s use blocks instead!Advantages: No need for subclassing May not need a new class at all Template can be changed dynamically
    42. 42. Template Method- (void)doSomethingUsingBlock:(dispatch_block_t)block { // Do something block(); // Do some more stuff}
    43. 43. Example Templates
    44. 44. Debug Mode+ (void)whileInDebug:(MyBlock)block {#if defined(DEBUG) NSParameterAssert(block); block();#endif}
    45. 45. Lock Handling// Python convenient lock handlerwith myLock: // Do something // Can’t forget to lock/unlock
    46. 46. Lock Handling+ (void)withLock:(NSLock)lock executeBlock:(MyBlock)block { NSParameterAssert(lock && block); [lock lock]; block(); [lock unlock]; }
    47. 47. Builder Pattern Some objects have complex structures that vary widely between uses Examples: Database tables, UITableView A block can define the construction of an object
    48. 48. Builder Pattern // Ruby on Rails database table construction create_table :person do |t| t.string :name, null: false t.integer :age, null: false t.float :weight end
    49. 49. Builder Pattern// Contrived example, but very feasible.// Creating a custom table view form.[RBTableView tableViewUsingBlock:^(RBTableView * t) { [t addStringField:@“name” required:YES]; [t addIntegerField:@“age” required:YES]; [t addFloatField:@“weight” required:NO];}];
    50. 50. Lockless ExclusionAccessorThread-sensitive code is called critical codeGCD allows for lockless-exclusion Lockless code is faster than lock code
    51. 51. Lockless ExclusionAccessorMulti-threading challenges: Multi-threaded code must be properly synchronized It’s easy to forget to add thread-safety code
    52. 52. Lockless ExclusionAccessorSolution: Have another object handle thread-safety Put critical code in a block Give the block to the thread-safety handler
    53. 53. Lockless ExclusionAccessor- (void)accessSharedDataAsync:(void(^)(id sharedData))block { NSParameterAssert(block); // myQueue must be a serial queue! dispatch_async(myQueue, ^{ block([self sharedData]); });}
    54. 54. Lockless ExclusionAccessor Shared Data SerialShared Data Manager Queue Block LEA C B A
    55. 55. Lockless ExclusionAccessor Shared Data SerialShared Data Manager Queue Block C LEA Block B Block A
    56. 56. Lockless ExclusionAccessor Shared Data SerialShared Data Manager Queue LEA Block Block A C Block B
    57. 57. Lockless ExclusionAccessor Shared Data SerialShared Data Manager Queue LEA Block Block A C Block B
    58. 58. Lockless ExclusionAccessor Shared Data SerialShared Data Manager Queue LEA Block A B Block C
    59. 59. Lockless ExclusionAccessor Shared Data SerialShared Data Manager Queue LEA Block A B Block C
    60. 60. Lockless ExclusionAccessor Shared Data SerialShared Data Manager Queue LEA Block C A B
    61. 61. Lockless ExclusionAccessor Shared Data SerialShared Data Manager Queue LEA Block C A B
    62. 62. Read/Write LEACode that only reads from shared memory doesn’tneed exclusive accessCode that writes to shared memory needs exclusiveaccessGCD barrier blocks and concurrent queues are aperfect solution
    63. 63. Read/Write LEA// Read-only LEA- (void)accessSharedDataReadOnlyAsync:(void(^)(id sharedData))block { NSParameterAssert(block); // myQueue must be a concurrent queue! dispatch_async([self myQueue], ^{ block([self sharedData]); });}
    64. 64. Read/Write LEA// Read/write LEA- (void)accessSharedDataReadWriteAsync:(void(^)(id sharedData))block { NSParameterAssert(block); // myQueue must be a concurrent queue! dispatch_barrier_async([self myQueue], ^{ block([self sharedData]); });}
    65. 65. Read/Write LEA// All-in-one R/W-LEA- (void)accessSharedDataAsyncReadOnly:(BOOL)readOnly withBlock:(void(^)(idsharedData))block { if (readOnly) dispatch_async([self myQueue], ^{ block([self sharedData]); }); else dispatch_barrier_async([self myQueue], ^{ block([self sharedData]); });}
    66. 66. Read/Write LEA Shared Data ConcurrentShared Data Manager Queue R/W-LEA Read Write Block
    67. 67. Read/Write LEA Shared Data ConcurrentShared Data Manager Queue Write R/W-LEA Block Read Block Read Block Read Block
    68. 68. Read/Write LEA Shared Data ConcurrentShared Data Manager Queue R/W-LEA Read Block Read Read Block Block Write Block
    69. 69. Read/Write LEA Shared Data ConcurrentShared Data Manager Queue Read R/W-LEA Block Read Read Read Block Block Block Write Block
    70. 70. Read/Write LEA Shared Data ConcurrentShared Data Manager Queue Read R/W-LEA Block Read Read Read Block Block Block Write Block
    71. 71. Read/Write LEA Shared Data ConcurrentShared Data Manager Queue Read R/W-LEA Block Read Read Read Block Block Block Write Block
    72. 72. Read/Write LEA Shared Data ConcurrentShared Data Manager Queue R/W-LEA Write Read Read Read Block Block Block Read Block
    73. 73. Read/Write LEA Shared Data ConcurrentShared Data Manager Queue R/W-LEA Write Read Read Read Block Block Block Read Block
    74. 74. Read/Write LEA Shared Data ConcurrentShared Data Manager Queue R/W-LEA Write Read Read Block Block
    75. 75. Read/Write LEA Shared Data ConcurrentShared Data Manager Queue R/W-LEA Write Read Read Block Block
    76. 76. HomeworkI have only touched the surface of what blocks can doExplore and find other design patterns you can convertto use blocks
    77. 77. Want to Learn More?Blocks are best learned by playing with themLearn Ruby “The Pickaxe”Learn Racket10 Uses for BlocksMy Blog
    78. 78. Questions?

    ×