很多 App 都有「每隔幾秒做一次某事」的需求,例如定期輪詢伺服器狀態、倒數計時、動畫幀更新。在 Cocoa 與 Cocoa Touch 環境中,最直接的答案就是 NSTimer。本文把它的使用流程、各參數意義,以及停止時機完整梳理一遍。
應用程式需要把某段程式碼排程到未來的特定時間執行,而且還希望能夠重複觸發,不必自己寫迴圈去 busy wait。
NSTimer 並不是一個獨立運作的執行緒,它必須掛載到一條 Run Loop 上才能被觸發。也就是說,若要在 Mac 或 iOS 應用中使用計時器,該執行緒就必須具備 Run Loop。主執行緒預設就有,因此在 App 生命週期內使用完全沒問題;但如果你在自行建立的背景執行緒裡使用,就要先確保那條執行緒跑起了 Run Loop。
計時器需要一個日期物件來表示「何時開始向目標送訊息」。最常見的寫法是用「現在起算 N 秒後」:
NSDate *scheduledTime = [NSDate dateWithTimeIntervalSinceNow:10.0];
這行程式碼表示:在本次呼叫之後的 10 秒,計時器才會進入活躍狀態。當然你也可以指定任何絕對時間點。
接著透過 initWithFireDate:interval:target:selector:userInfo:repeats: 建構物件:
NSString *customUserObject = @"To demo userInfo";
NSTimer *timer = [[NSTimer alloc] initWithFireDate:scheduledTime
interval:2
target:self
selector:@selector(task)
userInfo:customUserObject
repeats:YES];
@selector(方法名)。因為方法與計時器都在同一個物件裡,這裡可以直接用 self。YES 表示依 interval 反覆觸發,NO 則只觸發一次後自動失效。取得目前 Run Loop 的引用,再把計時器註冊進去:
NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
完成之後,10 秒後計時器啟動,此後每 2 秒就會呼叫一次 task 方法。
想中止計時器,只要送出 invalidate 訊息。這會把計時器從 Run Loop 中移除,之後就不會再觸發:
[timer invalidate];
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window = _window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSDate *scheduledTime = [NSDate dateWithTimeIntervalSinceNow:10.0];
NSString *customUserObject = @"To demo userInfo";
NSTimer *timer = [[NSTimer alloc] initWithFireDate:scheduledTime
interval:2
target:self
selector:@selector(task)
userInfo:customUserObject
repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
}
- (void)task:(id)sender {
NSTimer *localTimer = (NSTimer *)sender;
NSLog(@"Schedule task has executed with this user info: %@", [localTimer userInfo]);
}
@end
從 Xcode 編譯並執行這個 Mac 應用,觀察 Console 的輸出。每則訊息都帶有時間戳,可以清楚看到 2 秒的間隔節奏:
2012-01-19 15:23:28.651 Timer[31067:707] Schedule task has executed with this user info: To demo userInfo 2012-01-19 15:23:30.651 Timer[31067:707] Schedule task has executed with this user info: To demo userInfo 2012-01-19 15:23:32.651 Timer[31067:707] Schedule task has executed with this user info: To demo userInfo
第一,計時器會強引用它的 target,因此在 dealloc 之前若沒有 invalidate,物件可能永遠無法釋放,這是常見的記憶體洩漏來源。第二,若計時器要放在自建執行緒上,別忘了那條執行緒得先跑起 Run Loop。第三,在較新的 SDK 中,也可以考慮改用 GCD 的 dispatch_source_t,它在精度與跨執行緒使用上更靈活。