【问题标题】:Stopwatch glitches秒表故障
【发布时间】:2012-07-08 16:38:06
【问题描述】:

我最近做了一个秒表应用程序,它有一些小故障。

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

如果我连续按两次开始按钮,计时器的运行速度会提高一倍,而停止按钮将停止工作。

我该如何解决这个问题?

这是我的 .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];
}

【问题讨论】:

    标签: ios xcode nstimer stopwatch


    【解决方案1】:

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

    【讨论】:

    • userInterActonEnabled 在哪里?
    • 它是 UIButton 的一个属性。喜欢self.myButton.userInteractionEnabled = NO;
    【解决方案2】:

    您应该创建一个私有 BOOL 变量“isRunning”,当单击停止或启动时会检查该变量:

    - (IBAction)stop {
        if(!isRunning) return;
    
        [myTicker invalidate];
        [myTicker2 invalidate];
        [myTicker3 invalidate];
    
        self.isRunning = NO;
    }
    

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

    【讨论】:

    • 如何创建私有 BOOL 变量“isRunning”
    • 将此行添加到@interface(您还可以在其中定义您的 IBOutlets、NSTimers 等):BOOL isRunning。就是这样;-)
    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 2023-03-09
    • 2014-01-29
    • 2021-08-14
    • 2011-08-26
    • 2016-09-09
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多