2012-02-29 60 views
0

這是我的問題, 當我點擊開始按鈕計時器運行,當我點擊停止按鈕時,它停止。但是,當我點擊開始按鈕時,它會回到零。我希望啓動按鈕在計時器停在的地方繼續。NSTimer問題與我的秒錶

.h 

NSTimer *stopWatchTimer; 
    NSDate *startDate; 
    @property (nonatomic, retain) IBOutlet UILabel *stopWatchLabel; 
    - (IBAction)onStartPressed; 
    - (IBAction)onStopPressed; 
    - (IBAction)onResetPressed; 

.m 

    - (void)updateTimer 
    { 
    NSDate *currentDate = [NSDate date]; 
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"HH:mm:ss.SSS"]; 
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 
    NSString *timeString=[dateFormatter stringFromDate:timerDate]; 
    stopWatchLabel.text = timeString; 
    } 
    - (IBAction)onStartPressed { 
    startDate = [NSDate date]; 
    // Create the stop watch timer that fires every 10 ms 
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 
    target:self 
    selector:@selector(updateTimer) 
    userInfo:nil 
    repeats:YES]; 
    } 
    - (IBAction)onStopPressed { 
    [stopWatchTimer invalidate]; 
    stopWatchTimer = nil; 
    [self updateTimer]; 
    } 
    - (IBAction)onResetPressed { 
    stopWatchLabel.text = @」00:00:00:000″; 
    } 

請幫忙,謝謝

回答

0

你必須處理狀態的問題。一種狀態是啓動按鈕被按下,但復位按鈕尚未被按下。另一個狀態是按下開始按鈕,並且復位按鈕已經被按下。你可以做的一件事是創建一個iVar來跟蹤這個狀態。因此,使用一個BOOL這樣的:

首先聲明伊娃:

BOOL resetHasBeenPushed; 

值初始化爲NO。

那麼做到這一點

- (IBAction)onResetPressed { 
    stopWatchLabel.text = @」00:00:00:000″; 
    resetHasBeenPushed = YES; 

現在,您需要將其設置回NO,在某些時候,這可能會在啓動方法來完成:

- (IBAction)onStartPressed { 
    startDate = [NSDate date]; 
    // Create the stop watch timer that fires every 10 ms 
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 
    target:self 
    selector:@selector(updateTimer) 
    userInfo:nil 
    repeats:YES]; 
    resetHasBeenPushed = NO; 
} 
    } 

順便說一句,如果你在iVar中創建你的NSDateFormatter,你不需要重複初始化它。 Movethe以下行你INTI代碼,或osmewhere只運行一次:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 

UPDATE

試試這個:

- (IBAction)onStartPressed { 
    if (resetHasBeenPushed== YES) { 
     startDate = [NSDate date]; // This will reset the "clock" to the time start is set 
    } 

    // Create the stop watch timer that fires every 10 ms 
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 
    target:self 
    selector:@selector(updateTimer) 
    userInfo:nil 
    repeats:YES]; 
    }