Skip to content

Instantly share code, notes, and snippets.

@oleganza
Created December 2, 2010 21:12
Show Gist options
  • Save oleganza/726074 to your computer and use it in GitHub Desktop.
Save oleganza/726074 to your computer and use it in GitHub Desktop.
perform blocks on main thread after delay and cancel them when you please
@interface NSObject (OAObjectHelpers)
+ (id) performBlock:(void(^)())aBlock afterDelay:(NSTimeInterval)seconds;
+ (void) cancelPreviousPerformBlock:(id)aWrappingBlockHandle;
@end
@implementation NSObject (OAPerformBlockAfterDelay)
+ (id) performBlock:(void(^)())aBlock afterDelay:(NSTimeInterval)seconds
{
if (!aBlock) return nil;
__block BOOL cancelled = NO;
void (^aWrappingBlock)(BOOL) = ^(BOOL cancel){
if (cancel) {
cancelled = YES;
return;
}
if (!cancelled) aBlock();
};
aWrappingBlock = [[aWrappingBlock copy] autorelease]; // move to the heap
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1000000000*seconds)),
dispatch_get_main_queue(),
^{
aWrappingBlock(NO);
});
return aWrappingBlock;
}
+ (void) cancelPreviousPerformBlock:(id)aWrappingBlockHandle
{
if (!aWrappingBlockHandle) return;
void (^aWrappingBlock)(BOOL) = (void(^)(BOOL))aWrappingBlockHandle;
aWrappingBlock(YES);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment