dispatch_after取消方法

今天遇到个关于想终止这个dispatch_after里面代码块的执行,搜了一些资料发现系统没有提供dispatch_after的取消方法。那么怎么取消dispatch_after代码块的执行,或者用其他方法代替呢?

1.通过再封装达到取消dispatch_after代码块执行

typedef void(^WWDelayedBlockHandle) (BOOL cancel);
@property (nonatomic, assign) WWDelayedBlockHandle delayedBlockHandle;

//用再封装的延迟执行方法
_delayedBlockHandle = perform_block_after_delay(3.0, ^{
   NSLog(@"buttonAction_____3s后执行dispatch_after代码块中的内容");
});
//取消
cancel_delayed_block(_delayedBlockHandle);

static WWDelayedBlockHandle perform_block_after_delay(CGFloat seconds, dispatch_block_t block) {
    if (block == nil) {
        return nil;
    }
      
    __block dispatch_block_t blockToExecute = [block copy];
    __block WWDelayedBlockHandle delayHandleCopy = nil;
      
    WWDelayedBlockHandle delayHandle = ^(BOOL cancel) {
        if (!cancel && blockToExecute) {
            blockToExecute();
        }
          
        // Once the handle block is executed, canceled or not, we free blockToExecute and the handle.
        // Doing this here means that if the block is canceled, we aren't holding onto retained objects for any longer than necessary.
#if !__has_feature(objc_arc)
        [blockToExecute release];
        [delayHandleCopy release];
#endif
          
        blockToExecute = nil;
        delayHandleCopy = nil;
    };
    // delayHandle also needs to be moved to the heap.
    delayHandleCopy = [delayHandle copy];
      
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (nil != delayHandleCopy) {
            delayHandleCopy(NO);
        }
    });
      
    return delayHandleCopy;
}

static void cancel_delayed_block(WWDelayedBlockHandle delayedHandle) {
    if (nil == delayedHandle) {
        return;
    }
      
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        delayedHandle(YES);
    });
}

2.通过平替方法来达到延期执行方法可打断操作

//用系统提供的延迟执行方法来替换
[self performSelector:@selector(performTestAction) withObject:nil afterDelay:3];

//取消延迟执行
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(performTestAction) object:nil];

以上两种方式解决了我遇到的延迟方法打断执行的问题,本篇GitHubDemo,希望能帮到你...

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

推荐阅读更多精彩内容