Created
December 2, 2010 21:12
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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