我想創建一個「秒錶」類型的功能。我有一個標籤(顯示已用時間)和兩個按鈕(啓動和停止計時器)。開始和停止按鈕分別調用startTimer
和stopTimer
函數。定時器每秒鐘觸發並調用increaseTimerCount
函數。我也有一個ivar timerCount
,持續時間以秒爲單位。創建一個iOS計時器
- (void)increaseTimerCount
{
timerCountLabel.text = [NSString stringWithFormat:@"%d", timerCount++];
}
- (IBAction)startTimer
{
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(increaseTimerCount) userInfo:nil repeats:YES];
}
- (IBAction)stopTimer
{
[timer invalidate];
[timer release];
}
的問題是,似乎有當啓動按鈕被按下的延遲(這我假設是由於每個startTimer所調用時重新初始化定時器)。有什麼方法可以暫停並恢復計時器,而不會使其失效並重新創建它?或者做一個更好的/替代的方式?
謝謝。