这几天在写登录注册界面,不免要用到倒计时的内容。在以前我都是用NSTimer去写,但是有没有一种更好的方法去写呢。去网上百度了一下,终于找到了一种更好的方法去实现,就是GCD。
用GCD首先要知道几个属性
dispatch_source_t:是一个监视某些类型事件的对象。当这些事件发生时,它自动将一个block放入一个dispatch queue的执行例程中。
dispatch_source_set_timer:这是一个定时器的方法。
首先把所需要的创建的对象创建:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
__block int timeout=10; //倒计时时间
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _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(), ^{
//设置界面的按钮显示 根据自己需求设置
self.timerLabel.text = @"是否重新发送";
});
}else{
//int minutes = timeout / 60;
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%.2d秒后重新获取验证码", seconds];
//回到主界面
dispatch_async(dispatch_get_main_queue(), ^{
self.timerLabel.text = strTime;
});
dispatch_async(dispatch_get_main_queue(), ^{
//设置界面的按钮显示 根据自己需求设置
});
timeout--;
}
});
dispatch_resume(_timer);
完整的一个Demo我上传到github,有兴趣的同学可以看一下,相互学习。
https://github.com/sunyunfei/TimerDemo