秒表故障

时间:2012-07-08 16:38:06

标签: ios xcode nstimer stopwatch

我最近制作了秒表应用程序并且有一些故障。

如果我连续两次点击停止按钮,整个应用程序都会崩溃。

如果我连续两次点击开始按钮,计时器将以两倍的速度运行,停止按钮将停止工作。

如何解决此问题?

以下是我的.h文件中的代码:

    IBOutlet UILabel *time;
    IBOutlet UILabel *time1;
    IBOutlet UILabel *time2;

    NSTimer *myTicker;
    NSTimer *myTicker2;
    NSTimer *myTicker3;
}

- (IBAction)start;
- (IBAction)stop;
- (IBAction)reset;


- (void)showActivity;
- (void)showActivity1;
- (void)showActivity2;

@end

这是我在.m文件中的代码:

- (IBAction)start {
    myTicker = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];  

    myTicker2 = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(showActivity1) userInfo:nil repeats:YES];

    myTicker3 = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(showActivity2) userInfo:nil repeats:YES];        
}

- (IBAction)stop {
    [myTicker invalidate];
    [myTicker2 invalidate];
    [myTicker3 invalidate];
}

- (IBAction)reset {    
    time.text = @"00";
    time1.text = @"00";
    time2.text = @"00";
}

- (void)showActivity {    
    int currentTime = [time.text intValue];
    int newTime = currentTime + 1;
    if (newTime == 60) {
        newTime = 0;
    }
    time.text = [NSString stringWithFormat:@"%d", newTime];     
}

- (void)showActivity1 {
    int currentTime1 = [time1.text intValue];
    int newTime1 = currentTime1 + 1;
    if (newTime1 == 10) {
        newTime1 = 0;
    }
    time1.text = [NSString stringWithFormat:@"%d", newTime1];    
}

- (void)showActivity2 {
    int currentTime2 = [time2.text intValue];
    int newTime2 = currentTime2 + 1;
    time2.text = [NSString stringWithFormat:@"%d", newTime2];
}

2 个答案:

答案 0 :(得分:1)

userInterActionEnabled方法被触发时,将停止按钮的NO属性设置为YES,将开始按钮设置为-stop。然后切换并将停止按钮的userInterActionEnabled设置为YES,并在NO被触发时将开始按钮设置为-start

答案 1 :(得分:1)

你应该创建一个私有BOOL变量“isRunning”,当单击Stop或Start时会检查它:

- (IBAction)stop {
    if(!isRunning) return;

    [myTicker invalidate];
    [myTicker2 invalidate];
    [myTicker3 invalidate];

    self.isRunning = NO;
}

等。同样忽略用户交互通常是一个好主意(如CodaFi建议),但只能对抗症状;-)你真的应该做两个检查。