NSTimer 是 iOS 中做定時任務的常用工具,但它在多線程、RunLoop 與後台執行等方面有不少細節需要留意。本文從基本用法講到實戰注意事項。
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
其中 userInfo 是攜帶的用戶信息。不使用 scheduled 方式初始化的定時器,需要手動調用 addTimer:forMode: 把它添加到某個 RunLoop 中;而 scheduled 方式會以默認 mode 直接加入當前 RunLoop。
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(startFindApartment:) userInfo:nil repeats:YES]; // 或 NSTimer *myTimer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO]; [[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode];
定時器創建並加入 RunLoop 後,會在指定的 timeInterval 秒後自動觸發,也可以用 - (void)fire; 立即觸發。停止則調用 - (void)invalidate;,這是唯一能將計時器從 RunLoop 中移出的方法。
在主線程中,兩種初始化方式都可用;但在子線程中,只能使用 timerWithTimeInterval:,且不能靠 fire 啟動,而要讓 RunLoop 持續運行:
_timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(timeSchedule) userInfo:nil repeats:YES]; NSRunLoop* runLoop=[NSRunLoop currentRunLoop]; [runLoop addTimer:_timer forMode:NSDefaultRunLoopMode]; while([runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
1. NSTimer 會 retain 目標對象。無論一次性還是重複型定時器,都會對創建它的對象進行 retain。一次性定時器到點後會自行 invalidate,而重複型必須由開發者手動調用 invalidate,否則會導致對象無法釋放、造成洩漏。
2. NSTimer 必須加入 RunLoop 才能執行。在非主線程只創建並啟動定時器是不會運行的,除非把它加入該線程的 RunLoop 並啟動。主線程之所以能直接工作,是因為它默認已啟動了 RunLoop。
3. NSTimer 並不精確。當線程阻塞時它會延遲執行,延遲超過一個週期還會與下一次觸發合併。因此用它做長時間精確計時,誤差會不斷累積。
4. 後台執行需要借助音頻特權。默認進入後台會暫停,若要在後台繼續,可在 Info.plist 添加「Required background modes」並設為「App plays audio」,同時配置 AVAudioSession 的 Playback 類別,並在進入後台時申請後台任務時間。這種做法會犧牲一定性能,需謹慎使用。