创建一个可以取消执行的 block,

创建一个类,将要执行的 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容