priore

Cancellable dispatch_after

Mar 4th, 2016
734
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #ifndef dispatch_cancellable_block_h
  2. #define dispatch_cancellable_block_h
  3.  
  4. #import <Foundation/Foundation.h>
  5.  
  6. typedef void(^dispatch_cancelable_block_t)(BOOL cancel);
  7.  
  8. NS_INLINE dispatch_cancelable_block_t dispatch_after_delay(NSTimeInterval delay, dispatch_block_t block) {
  9.     if (block == nil) {
  10.         return nil;
  11.     }
  12.    
  13.     // First we have to create a new dispatch_cancelable_block_t and we also need to copy the block given (if you want more explanations about the __block storage type, read this: https://developer.apple.com/library/ios/documentation/cocoa/conceptual/Blocks/Articles/bxVariables.html#//apple_ref/doc/uid/TP40007502-CH6-SW6
  14.     __block dispatch_cancelable_block_t cancelableBlock = nil;
  15.     __block dispatch_block_t originalBlock = [block copy];
  16.    
  17.     // This block will be executed in NOW() + delay
  18.     dispatch_cancelable_block_t delayBlock = ^(BOOL cancel){
  19.         if (cancel == NO && originalBlock) {
  20.             originalBlock();
  21.         }
  22.        
  23.         // We don't want to hold any objects in the memory
  24.         originalBlock = nil;
  25.     };
  26.    
  27.     cancelableBlock = [delayBlock copy];
  28.    
  29.     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  30.         // We are now in the future (NOW() + delay). It means the block hasn't been canceled so we can execute it
  31.         if (cancelableBlock) {
  32.             cancelableBlock(NO);
  33.             cancelableBlock = nil;
  34.         }
  35.     });
  36.    
  37.     return cancelableBlock;
  38. }
  39.  
  40. NS_INLINE void cancel_block(dispatch_cancelable_block_t block) {
  41.     if (block == nil) {
  42.         return;
  43.     }
  44.    
  45.     block(YES);
  46.     block = nil;
  47. }
  48.  
  49. #endif /* dispatch_cancellable_block_h */
RAW Paste Data