您的位置:首页 > 其它

使用GCD 实现倒计时功能

2018-01-19 15:02 357 查看
前段时间需要实现倒计时功能,找了一下网上用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。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  倒计时--GCD实现