GCD方法
///定时器
@property (nonatomic,strong) dispatch_source_t timer;
例如:启动页倒计时
- (void)createTimerWithTime:(NSString *)time{
//设置倒计时时间
//通过检验发现,方法调用后,timeout会先自动-1,所以如果从15秒开始倒计时timeout应该写16
//__block 如果修饰指针时,指针相当于弱引用,指针对指向的对象不产生引用计数的影响
__block int timeout = [time intValue]+1;
//获取全局队列
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);
self.timer = timer;
//设置触发的间隔时间
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
WS(weakSelf);
//设置定时器的触发事件
dispatch_source_set_event_handler(timer, ^{
//1. 每调用一次 时间-1s
timeout --;
if (timeout <= 0) {
//关闭定时器
dispatch_source_cancel(timer);
//在主线程中对button进行修改操作
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.timeButton setTitle:@"跳过" forState:UIControlStateNormal];
[weakSelf delayedLoadVC];
});
}else {
//处于正在倒计时,在主线程中刷新button上的title,时间-1秒
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.timeButton setTitle:[NSString stringWithFormat:@"跳过 %d",timeout] forState:UIControlStateNormal];
});
}
});
dispatch_resume(timer);
}
关闭定时器
dispatch_source_cancel(self.timer);
网友评论