「每隔幾秒執行某個方法」是再常見不過的需求,iOS 提供了三條路:NSTimer、CADisplayLink 與 GCD 的 dispatch source。三者精度與適用場景差異不小,選錯容易踩坑。
先準備一個被呼叫的方法作為測試目標:
- (void)reloop {
NSLog(@"循環執行");
}
最直覺的做法,有兩種加入 runloop 的方式。
A. 自動加入主 runloop
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2
target:self
selector:@selector(reloop)
userInfo:nil
repeats:YES];
[timer fire]; // 立即觸發一次
[timer invalidate]; // 停止後才需要釋放
B. 手動加入 runloop
NSTimer *timer = [NSTimer timerWithTimeInterval:2
target:self
selector:@selector(reloop)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
要注意兩點:一是 NSTimer 會被 runloop 強引用 target,重複執行時必須在 dealloc 前 invalidate,否則物件永遠不會釋放;二是它不 guarantee 精度,若執行緒當時忙碌,觸發時間會被延後,所以用來做動畫或音訊同步並不合適。
CADisplayLink 與螢幕刷新率同步,在 runloop 以特定模式註冊後,每次畫面刷新結束就會回呼一次 selector。iOS 裝置刷新率一般為 60 次/秒,因此它天生適合做逐幀繪製。
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self
selector:@selector(reloop)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
// 不再需要時務必停止並清空
[displayLink invalidate];
displayLink = nil;
精度雖高,但仍有前提:若回呼方法太耗時、超過一個刷新週期,就會被跳過若干次;CPU 忙碌時也一樣。因此它適合用於「畫面持續重繪」的場景(例如影片逐幀渲染、自轉地球、計分動畫),不適合當一般的業務定時器。
只執行一次(延遲)
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){
[self reloop];
});
重複執行
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, ^{
[self reloop];
});
dispatch_resume(_timer);
這裡有兩個關鍵細節:起始時間若用 dispatch_walltime,就不會受系統時間調整影響,適合做「每天固定時間執行」這類需求;而 dispatch_source 建立後處於暫停狀態,一定要呼叫 dispatch_resume 才會開始跑。
需要「精準逐幀」用 CADisplayLink;只是「每隔幾秒做一件事」用 GCD dispatch source,它不受 runloop 模式影響,在滑動列表時也不會被延後;若要跨 iOS 版本相容、或只是簡單的倒數,NSTimer 最省事。三者之中,GCD 的準確性與穩定性最佳,是目前最推薦的選擇。