最近在製作一個小專案時需要用到計時器功能,也就是 NSTimer 類別。過程中遇到了一些小問題,最終靠著自己摸索逐一克服。以下就來總結我對 NSTimer 的學習與理解。
先來看需求:介面很簡單,兩個 UIButton(開始與暫停),一個顯示起始倒數「20」的標籤。按下開始按鈕時倒數啟動,按下暫停時停止;當倒數歸零時,彈出對話框提示時間已到。
需求雖簡單,但實作時卻出現了幾個新手常犯的錯誤:暫停鍵無法多次點擊、開始鍵也無法多次點擊。相信剛接觸 NSTimer 的人多少都會遇到這些狀況。
@interface sdsViewController : UIViewController <UIAlertViewDelegate>
//定義一個定時器,作為實例變量
@property(nonatomic,retain) NSTimer *timer;
//顯示倒計時當前狀態
@property (retain, nonatomic) IBOutlet UILabel *timeDisplay;
//開始按鈕,響應的 action
- (IBAction)startTime:(id)sender;
//暫停按鈕響應的 action
- (IBAction)stopTime:(id)sender;
@end
開始按鈕的響應程式碼:
- (IBAction)startTime:(id)sender {
//如果定時器物件不存在,則建立一個並啟動
if(!_timer){
//建立一個定時器,直接加到當前訊息循環中
_timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTimeAtTimedisplay) userInfo:nil repeats:YES];
}
}
結束按鈕的響應程式碼:
- (IBAction)stopTime:(id)sender {
if (_timer) {
//如果定時器在運行
if ([self.timer isValid]) {
[self.timer invalidate];
//這行代碼很關鍵
_timer=nil;
}
}
}
這裡的關鍵在於:停止時呼叫 invalidate 之後,還必須把 _timer 設為 nil,否則下次點擊開始時,if(!_timer) 判斷會失敗,定時器便無法重新建立,這正是「只能點擊一次」的根源。
以下兩個便利構造器會建立定時器並自動加入當前運行循環,等同在指定秒數後自動啟動:
+ scheduledTimerWithTimeInterval:invocation:repeats:
+ scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
而這兩個方法只是建立,並不會加入運行循環,之後必須手動呼叫 NSRunLoop 的 addTimer:forMode: 才行:
+ timerWithTimeInterval:invocation:repeats:
+ timerWithTimeInterval:target:selector:userInfo:repeats:
手動加入的寫法:
_timer=[NSTimer timerWithTimeInterval:10 target:self selector:@selector(changeTimeAtTimedisplay) userInfo:nil repeats:YES];
NSRunLoop *runloop=[NSRunLoop currentRunLoop];
[runloop addTimer:_timer forMode:NSDefaultRunLoopMode];
兩種寫法的最終效果相同。
許多人誤以為 fire 是用來啟動定時器的,其實並非如此。從初始化方法可看出,定時器建立後便會在恰當時間自動啟動。根據官方文件,fire 的用途是:能在不打亂週期性排程的前提下手動觸發一個重複的定時器;而對於非重複的定時器,觸發後會自動失效,即使排定的觸發時間尚未到來。換言之,它並不是「啟動定時器」這麼單純。