NSTimer我的秒表问题

时间:2012-02-29 19:53:22

标签: xcode4.2 nstimer nsdateformatter xcode-storyboard

这是我的问题, 当我点击开始按钮时,计时器运行,当我点击停止按钮时它停止。但是当我点击开始按钮时,它会回到零。我希望启动按钮能在计时器停止的地方继续。

.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″;
    }

请帮助谢谢

1 个答案:

答案 0 :(得分:0)

处理状态时遇到问题。一种状态是按下启动按钮,但是之前没有按下重置按钮。另一种状态是按下启动按钮,并且在它之前按下了重置按钮。您可以做的一件事是创建一个iVar来跟踪这种状态。所以使用这样的BOOL:

首先声明iVar:

BOOL resetHasBeenPushed;

将值初始化为NO。

然后这样做

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

现在你需要在某个时候将它设置回NO,这可能在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,则不需要重复初始化它。将以下行移至您的inti代码,或osmewhere只运行一次:

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

更新

试试这个:

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