gcd 实现计时器和倒计时
gcd 实现计时器和倒计时
倒计时
-(void)startTime:(int)time{
__block int timeout=time; //倒计时时间
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
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(), ^{
});
}else{
// int minutes = timeout / 60;
int seconds = timeout % 60;
int minutes = timeout / 60;
NSString *minuTime = [NSString stringWithFormat:@"%.2d", minutes];
NSString *sccondTime = [NSString stringWithFormat:@"%.2d", seconds];
dispatch_async(dispatch_get_main_queue(), ^{
//设置界面的按钮显示 根据自己需求设置
NSLog(@"____%@____%@",minuTime,sccondTime);
self.timeLabel.text = [NSString stringWithFormat:@"%@: %@",minuTime,sccondTime];
});
timeout--;
}
});
dispatch_resume(timer);
}
- (void)endCount{
dispatch_source_cancel(timer);
}
计时器
- (void)startCount{
if (!_isStart) {
[self startToCountTime];
_isPause = NO;
}else
{
dispatch_suspend(timer);
_isPause = YES;
}
_isStart = !_isStart;
}
- (void)endCount{
if (_isCreat){
if (_isPause == YES) {
dispatch_resume(timer);
}
dispatch_source_cancel(timer);
_timeLabel.text = @"00:00:00";
_isStart = NO;
_timeCount = 0;
_isCreat = NO;
}
}
- (void)startToCountTime
{
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, globalQueue);
_isCreat = YES;
// 每秒执行一次
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(timer, ^{
int hours = _timeCount / 3600;
int minutes = (_timeCount - (3600*hours)) / 60;
int seconds = _timeCount%60;
NSString *strTime = [NSString stringWithFormat:@"%.2d:%.2d",minutes,seconds];
dispatch_async(dispatch_get_main_queue(), ^{
// ======在这根据自己的需求去刷新UI==============
_timeLabel.text = strTime;
});
_timeCount ++;
});
dispatch_resume(timer);
}