- (void)getNumBtnActionWithTimeout:(NSInteger)timeout{
__block NSInteger totalSecond = timeout;
//全局队列 默认优先级
dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//定时器模式 事件源
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
//NSEC_PER_SEC是秒,*1是每秒
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), NSEC_PER_SEC * 1, 0);
//设置响应dispatch源事件的block,在dispatch源指定的队列上运行
dispatch_source_set_event_handler(timer, ^{
//回调主线程,在主线程中操作UI
if (totalSecond > 0) {
int hours = (int)(totalSecond/3600);
int minute = (int)(totalSecond-hours*3600)/60;
int second = (int)totalSecond-hours*3600-minute*60;
dispatch_sync(dispatch_get_main_queue(), ^{
_probationLabel.text = [NSString stringWithFormat:@"%d : %d : %d",hours,minute,second];
});
totalSecond--;
}
else
{
//这句话必须写否则会出问题
dispatch_source_cancel(timer);
}
;
});
//启动源
dispatch_resume(timer);
}
网友评论