搜索
您的当前位置:首页正文

GCD创建定时器的记录

来源:知库网
GCD定时器

在我们的平时开发中经常会用到定时器 ,相对于NSTimer实现的定时器,GCD定时器记录的时间相对要精确一些。而且不用考虑内存释放的问题。

以下是GCD实现基本的获取验证码的倒计时功能
直接上代码了

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.but = [[UIButton alloc] initWithFrame:CGRectMake(self.view.center.x, self.view.center.y, 100, 50)];
//    self.but.backgroundColor = [UIColor redColor];
    [self.but setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [self.but setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.but.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.but addTarget:self action:@selector(tapClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.but];
}

- (void)tapClick:(UIButton*)but{

    [self playGCDTimer];
}

- (void)playGCDTimer{
    
    __block NSInteger time = 59;
    //全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    //创建timer 类型的定时器 (DISPATCH_SOURCE_TYPE_TIMER)
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

    //设置定时器的各种属性(何时开始,间隔多久执行)
    // GCD 的时间参数一般为纳秒 (1 秒 = 10 的 9 次方 纳秒)
    // 指定定时器开始的时间和间隔的时间
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    
    //任务回调
    dispatch_source_set_event_handler(timer, ^{
        
        if (time <= 0) {
            
            dispatch_source_cancel(timer);//关闭定时器
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.but setTitle:@"重新发送" forState:UIControlStateNormal];
                self.but.userInteractionEnabled = YES;
                
            });
        }else{
            
            int seconds = time % 60;
            dispatch_sync(dispatch_get_main_queue(), ^{
               
                [self.but setTitle:[NSString stringWithFormat:@"重新发送(%.2d)",seconds] forState:UIControlStateNormal];
                self.but.userInteractionEnabled = NO;//验证码获取时禁止用户点击
            });
        }
        time--;
    });
    
    // 开始定时器任务(定时器默认开始是暂停的,需要复位开启)
    dispatch_resume(timer);
}

好了GCD创建定时器的基本方法就介绍完了

Top