Dispatch after
Objc version
#import <Foundation/Foundation.h>
@interface BoolNum:NSObject
@property(nonatomic) BOOL isCancel;
@end
@implementation BoolNum
@end
@interface Solution:NSObject
+ (BoolNum*)dispatchAfterWithCancel:(NSInteger)delayTime block:(void(^)())block;
@end
@implementationSolution
+ (BoolNum*)dispatchAfterWithCancel:(NSInteger)delayTime block:(void(^)())block {
BoolNum* obj = [[BoolNum alloc] init];
obj.isCancel = NO;
void(^myBlock)() = ^{
if(obj.isCancel == NO) {
block();
}
};
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime *NSEC_PER_SEC)),
dispatch_get_global_queue(0,0),
^{
myBlock();
});
return obj;
}
@end
int main(intargc,constchar* argv[]) {
@autoreleasepool{
NSLog(@"Hello, World!");
BoolNum* obj = [Solution dispatchAfterWithCancel:2 block:^{
NSLog(@"xxx");
}];
obj.isCancel =YES;
sleep(3);
}
return0;
}
Swift version