使用GCD 实现倒计时功能

前段时间需要实现倒计时功能,找了一下网上用NSTimer的比较多,但是实际上,NSTimer的计算倒数不准确,NSTimer受runloop的影响,由于runloop需要处理很多任务,导致NSTimer的精度降低。所有就考虑用GCD来实现此功能。实现后发现确实比NSTimer准确,而且也不麻烦,不废话 上代码。

先创建一个source源

@property (nonatomic, strong) dispatch_source_t countdownTimer;

这个表示点击时间
然后再写一个方法,用来执行倒计时功能

-(void)countDownWithTimer:(dispatch_source_t)timer timeInterval:(NSTimeInterval)timeInterval complete:(void(^)())completeBlock progress:(void(^)(int mDay, int mHours, int mMinute, int mSecond))progressBlock{
    __block int timeout = timeInterval; //倒计时时间
    if (timeout!=0) {
        dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(timer, ^{
            if(timeout<=0){ //倒计时结束,关闭
                dispatch_source_cancel(timer);
                dispatch_async(dispatch_get_main_queue(), ^{ // block 回调
                    if (completeBlock) {
                        completeBlock();
                    }
                });
            }else{
                int days = (int)(timeout/(3600*24));
                int hours = (int)((timeout-days*24*3600)/3600);
                int minute = (int)(timeout-days*24*3600-hours*3600)/60;
                int second = timeout-days*24*3600-hours*3600-minute*60;
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (progressBlock) { //进度回调
                        progressBlock(days, hours, minute, second);
                    }
                });
                timeout--;
            }
        });
        dispatch_resume(timer);
    }
}

第一个参数就是我们的source源,第二个参数是需要倒计时的时间 如60秒。

然后写调用倒计时方法的方法

// 调用方法
-(void)resetCountdown:(NSInteger)time{
    [self cancelCountdownTimer];// 取消操作
    NSInteger count = time;
        // 创建一个队列
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _countdownTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        [self countDownWithTimer:_countdownTimer timeInterval:count complete:^{
            // 完成执行操作
        } progress:^(int mDay, int mHours, int mMinute, int mSecond) {
            NSLog(@"倒计时:%d", mSecond);
            // 倒计时

        }];
}

最后写一个取消方法

// 取消操作
-(void)cancelCountdownTimer{
    if (_countdownTimer) {
        dispatch_source_cancel(_countdownTimer);
        _countdownTimer = nil;
    }
}

这样 就完成了GCD的倒计时实现方法
so finish。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值