dispatch_after取消方法

今天遇到個(gè)關(guān)于想終止這個(gè)dispatch_after里面代碼塊的執(zhí)行,搜了一些資料發(fā)現(xiàn)系統(tǒng)沒有提供dispatch_after的取消方法。那么怎么取消dispatch_after代碼塊的執(zhí)行,或者用其他方法代替呢?

1.通過再封裝達(dá)到取消dispatch_after代碼塊執(zhí)行

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

//用再封裝的延遲執(zhí)行方法
_delayedBlockHandle = perform_block_after_delay(3.0, ^{
   NSLog(@"buttonAction_____3s后執(zhí)行dispatch_after代碼塊中的內(nèi)容");
});
//取消
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.通過平替方法來達(dá)到延期執(zhí)行方法可打斷操作

//用系統(tǒng)提供的延遲執(zhí)行方法來替換
[self performSelector:@selector(performTestAction) withObject:nil afterDelay:3];

//取消延遲執(zhí)行
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(performTestAction) object:nil];

以上兩種方式解決了我遇到的延遲方法打斷執(zhí)行的問題,本篇GitHubDemo,希望能幫到你...

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容