美文网首页
重写dispatch_after,使其可以手动暂停

重写dispatch_after,使其可以手动暂停

作者: jlnu_wjy | 来源:发表于2018-12-06 17:10 被阅读3次

当我们使用GCD的dispatch_after的时候,我们是没办法手动终止的,这样如果想提前终止一段时间后的方法执行,就要我们进行重写这个方法, 直接上代码

在controller.m里

#import "MainViewController.h"

#import "SecondViewController.h"

typedef void(^PDDelayedBlockHandle)(BOOL cancel);

@interface MainViewController ()

@property (nonatomic, assign) PDDelayedBlockHandle delayedBlockHandle;

@end

dispatch_after重写的方法

staticPDDelayedBlockHandleperform_block_after_delay(CGFloatseconds,dispatch_block_tblock) {

    if(block ==nil) {

        returnnil;

    }

    __blockdispatch_block_tblockToExecute = [blockcopy];

    __blockPDDelayedBlockHandledelayHandleCopy =nil;

    PDDelayedBlockHandledelayHandle = ^(BOOLcancel) {

        if(!cancel && blockToExecute) {

            blockToExecute();

        }

        blockToExecute =nil;

        delayHandleCopy =nil;

    };

    delayHandleCopy = [delayHandlecopy];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC), dispatch_get_main_queue(), ^{

        if(nil!= delayHandleCopy) {

            delayHandleCopy(NO);

        }

    });

    returndelayHandleCopy;

}

dispatch_after终止方法

staticvoidcancel_delayed_block(PDDelayedBlockHandledelayedHandle) {

    if(nil== delayedHandle) {

        return;

    }

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        delayedHandle(YES);

    });

}

例子引用

- (void)viewDidLoad {

    [super viewDidLoad];

    self.title=@"111";

    self.view.backgroundColor = [UIColor grayColor];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

    btn.frame=CGRectMake(30,100,80,40);

    btn.backgroundColor = [UIColor grayColor];

    [btnaddTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];

    [btnsetTitle:@"我同意" forState:UIControlStateNormal];

    [self.view addSubview:btn];

}

- (void)click{

    _delayedBlockHandle = perform_block_after_delay(8, ^{

        SecondViewController *sec = [[SecondViewController alloc] init];

        [self.navigationController pushViewController:sec animated:NO];

    });

    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];

    btn1.frame = CGRectMake(30, 200, self.view.frame.size.width - 60, 40);

    btn1.backgroundColor = [UIColor grayColor];

    [btn1addTarget:self action:@selector(toSecond) forControlEvents:UIControlEventTouchUpInside];

    [btn1setTitle:@"8s后跳转页面,也可以点我跳转" forState:UIControlStateNormal];

    [self.view addSubview:btn1];

}

- (void)toSecond{

    cancel_delayed_block(_delayedBlockHandle);

    SecondViewController *sec = [[SecondViewController alloc] init];

    [self.navigationController pushViewController:sec animated:NO];

}

相关文章

网友评论

      本文标题:重写dispatch_after,使其可以手动暂停

      本文链接:https://www.haomeiwen.com/subject/dkwocqtx.html