2012-02-29 12 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

ありがとうございました。 1つの状態は、開始ボタンが押されたが、その前にリセットボタンが押されていないことである。別の状態は、開始ボタンが押され、リセットボタンがその前に押されたことである。あなたができることの1つは、この状態を追跡するiVarを作成することです。したがって、このようにBOOLを使用します。

まずIVARを宣言:

BOOL resetHasBeenPushed; 

はNOに値を初期化します。

は、その後、あなたがいくつかの点で、バックNOに設定する必要があります今、この

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

行い、そのは、startメソッドで実行される可能性があります場合は、ところで

- (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:

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

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

UPDATE

はこれを試してみてください