一.延时执行的几种方式
最近发现扫描宝挺好用,将手写的几种延时方式发出来分享一下:
二.GCD写的定时器
- (void)startTimerWithDelay:(NSInteger)delayTime passOneSeconds:(void(^)(int currentTime))oneSecondsPassBlock stop:(void(^)())stopBlock{
倒计时时间自定
__block int timeout = delayTime;
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(), ^{
//这里调用结束的Blcok
if(stopBlock){
stopBlock();
}
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
//倒计时中,每过一秒调用过去1s的block
if(oneSecondsPassBlock){
oneSecondsPassBlock(timeout);
}
});
timeout--;
}
});
dispatch_resume(_timer);
}