
開發中經常會遇到「延遲一段時間後執行某方法」或「按固定週期反覆執行」的需求,這時就需要計時器。iOS 上能勝任這件事的方案不少,最常見的是三種:NSTimer、CADisplayLink 與 GCD。
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(action:)
userInfo:nil
repeats:NO];參數含義:
[timer invalidate];
注意:建立計時器後,target 的計數會 +1,執行完畢自動 -1。若是循環執行,就必須手動關閉,否則計數不會歸位;一次性計時器則可以省掉這步。
存在延遲:無論一次性還是週期性,實際觸發時間都與所加入的 RunLoop 及其 Mode 有關。若該 RunLoop 正在跑一段連續運算,timer 就會被延後。週期性 timer 若延遲超過一個週期,會在延遲結束後立刻補觸發一次,之後照原定週期繼續。
必須加入 RunLoop:用上面的 scheduledTimerWithTimeInterval: 建立時,會自動加入主 RunLoop 的 NSDefaultRunLoopMode。若改用下面的寫法,就得手動加入:
NSTimer *timer = [NSTimer timerWithTimeInterval:5
target:self
selector:@selector(timerAction)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];self.displayLink = [CADisplayLink displayLinkWithTarget:self
selector:@selector(handleDisplayLink:)];
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];[self.displayLink invalidate]; self.displayLink = nil;
把 CADisplayLink 加入 runloop 後,selector 就會被週期性呼叫,效果類似啟動了一個重複的 NSTimer;執行 invalidate 後它會自 runloop 中移除,呼叫隨之停止,也對應 NSTimer 的 invalidate。
與螢幕刷新同步:CADisplayLink 是一個讓你能以螢幕刷新率為頻率把內容畫到螢幕上的計時器類。以特定 Mode 註冊到 runloop 後,每次螢幕內容刷新結束,runloop 就會向它的 target 發送一次 selector 訊息。iOS 裝置的螢幕刷新率一般為 60 次/秒。
精度與延遲:螢幕刷新頻率固定,因此正常情況下 CADisplayLink 每次刷新都會被呼叫,精度相當高。但若被呼叫的方法太耗時、超過一個刷新週期,就會跳過若干次回調;CPU 過於繁忙、無法維持 60fps 時同樣會跳過,跳過的次數取決於繁忙程度。
適用場景:從原理不難看出,它適合需要持續重繪的介面,例如影片播放時不斷取下一幀送去渲染。
frameInterval:NSInteger,設定每隔幾幀才呼叫一次 selector,預設為 1,即每幀都呼叫。
duration:唯讀的 CFTimeInterval,代表兩次螢幕刷新之間的間隔。要注意它是在 target 的 selector 首次被呼叫之後才會被賦值。呼叫間隔的計算方式是:呼叫間隔 = duration × frameInterval。
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// 執行事件
});NSTimeInterval period = 1.0; // 設定時間間隔
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), period * NSEC_PER_SEC, 0); // 每秒執行
dispatch_source_set_event_handler(_timer, ^{
// 在這裡執行事件
});
dispatch_resume(_timer);GCD 這部分的資料網上相對零散,我自己也仍在學習,後續會再補充。