NSTimer 定時(shí)器易受 RunLoop模式影響導(dǎo)致定時(shí)器不準(zhǔn)確惋砂。
dispatch_source_t timer;
-(void)runGCDTimer
{
NSLog(@"click run GCD");
__block int count = 0;
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
uint64_t interval = (uint64_t)(1.0 *NSEC_PER_SEC);
dispatch_source_set_timer(timer, start, interval, 0);
dispatch_source_set_event_handler(timer, ^{
NSLog(@"------------:%@",[NSThread currentThread]);
count ++;
if (count == 5) {
dispatch_source_cancel(timer);
timer = nil;
}
});
dispatch_resume(timer);
}