2012-02-29 63 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]; 
    }