1.NSTimer实现倒计时的方式
WRXBtnSetTitle(self.btntime, @(60).stringValue);
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTopLabel) userInfo:nil repeats:YES];
}
- (void)updateTopLabel {
_topCount -= 1;
WRXBtnSetTitle(self.btntime, @(_topCount).stringValue);
if (_topCount == 0) {
[self.timer invalidate];
}
}
2.GCD实现倒计时的方式
- (void)setupGCD {
self.bottomLabel.text = @"60";
__block NSInteger bottomCount = 61;
//获取全局队列
dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//创建一个定时器,并将定时器的任务交给全局队列执行
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, global);
// 设置触发的间隔时间 1.0秒执行一次 0秒误差
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
__weak typeof(self)weakSelf = self;
dispatch_source_set_event_handler(timer, ^{
if (bottomCount <= 0) {
//关闭定时器
dispatch_source_cancel(timer);
}else {
bottomCount -= 1;
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.bottomLabel.text = [NSString stringWithFormat:@"%ld",bottomCount];
});
}
});
dispatch_resume(timer);
}
网友评论