倒计时 定时器 timer
-(void)gcdTimeStartTime:(NSInteger)startTime withBlock:(void(^)(NSInteger time))currentTime {
dispatch_queue_t queue = dispatch_get_main_queue();
__block dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
__block NSInteger count = startTime;
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
count --;
currentTime(count);
if (count == 0) {
dispatch_source_cancel(timer);
}
});
dispatch_resume(timer);
}
循环执行定时器
@property (nonatomic ,strong) dispatch_source_t timer;// 注意:此处应该使用强引用 strong
-------------------------------------------------------------------------------
/**
gcd 事件函数
@param sleepTime 每多少秒发生一次
@param currentTime 当前是第几次
*/
-(void)gcdEventTime:(NSInteger)sleepTime withBlock:(void(^)(NSInteger time))currentTime {
if (self.timer) {
return;
}
dispatch_queue_t queue = dispatch_get_main_queue();
__block dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
__block NSInteger count = 0;
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, sleepTime * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
count ++;
currentTime(count);
});
dispatch_resume(timer);
self.timer = timer;
}
// 取消定时器
-(void)cancelTimer {
if (self.timer) {
dispatch_source_cancel(self.timer);
}
}
网友评论