您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

NSTimer 排程與重複執行任務的完整做法

編輯:iOS 技巧大全

很多 App 都有「每隔幾秒做一次某事」的需求,例如定期輪詢伺服器狀態、倒數計時、動畫幀更新。在 Cocoa 與 Cocoa Touch 環境中,最直接的答案就是 NSTimer。本文把它的使用流程、各參數意義,以及停止時機完整梳理一遍。

要解決的問題

應用程式需要把某段程式碼排程到未來的特定時間執行,而且還希望能夠重複觸發,不必自己寫迴圈去 busy wait。

先確認前提:一定要有 Run Loop

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];

各參數說明

  • fireDate:日期物件,決定計時器何時第一次觸發。
  • interval:之後每次觸發之間要等待的秒數。
  • target:真正要接收訊息的物件。
  • selector:要呼叫的方法,寫成 @selector(方法名)。因為方法與計時器都在同一個物件裡,這裡可以直接用 self。
  • userInfo:任意型別的自訂資料,會在觸發時原封不動地隨計時器傳進來。範例用了字串,實務上更常傳字典,方便承載較複雜的上下文。
  • repeats:YES 表示依 interval 反覆觸發,NO 則只觸發一次後自動失效。

第三步:掛到 Run Loop 上

取得目前 Run Loop 的引用,再把計時器註冊進去:

NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];

完成之後,10 秒後計時器啟動,此後每 2 秒就會呼叫一次 task 方法。

如何停止

想中止計時器,只要送出 invalidate 訊息。這會把計時器從 Run Loop 中移除,之後就不會再觸發:

[timer invalidate];

完整範例(AppDelegate)

#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,它在精度與跨執行緒使用上更靈活。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved