iOS 中计时器的使用心得
1. NSTimer
使用NSTimer开启的计时器,如果拖动scrollView会导致计时器暂停,并且锁屏的时候必须暂停计时器,否则抛异常.
暂停计时器方法 [_sTimer setFireDate:[NSDate distantFuture]];
恢复计时器方法 [_sTimer setFireDate:[NSDate distantPast]];
_sTimer = [NSTimer scheduledTimerWithTimeInterval:interval
target:timerTarget
selector:@selector(fireTimer)
userInfo:userInfo
repeats:repeats];
[[NSRunLoop mainRunLoop] addTimer:_sTimer forMode:NSRunLoopCommonModes];
2.使用GCD开启的计时器,如果拖动scrollView,不会影响计时器的执行.但是,在iPad Mini的低版本上,苹果没有对其进行优化,使用这种方式开启的计时器会阻塞UI的响应事件.
//开启子线程加载曲谱 uint64_t interval = PerSecondTime * NSEC_PER_SEC; dispatch_queue_t queue = dispatch_queue_create("timerQueue", 0); _timers = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(_timers, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0); MLWeakSelf; dispatch_source_set_event_handler(_timers, ^() { // NSLog(@"Timer %@", [NSThread currentThread]); [weakSelf fireTimer]; }); dispatch_resume(_timers);