创建一个类,将要执行的 block 封装起来,然后类的内部有一个 _isCanceled 变量,在执行的时候,检查这个变量,如果 _isCanceled 被设置成 YES 了,则退出执行。
typedef void (^Block)();
@interface CancelableObject : NSObject
- (id)initWithBlock:(Block)block;
- (void)start;
- (void)cancel;
@end
@implementation CancelableObject {
BOOL _isCanceled;
Block _block;
}
- (id)initWithBlock:(Block)block {
self = [super init];
if (self != nil) {
_isCanceled = NO;
_block = block;
}
return self;
}
- (void)start {
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(0, 0),
^{
if (weakSelf) {
typeof(self) strongSelf = weakSelf;
if (!strongSelf->_isCanceled) {
(strongSelf->_block)();
}
}
});
}
- (void)cancel {
_isCanceled = YES;
}
@end