2012-07-08 58 views
1

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

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

如果我连续两次点击启动按钮,计时器将运行两次,停止按钮将停止工作。

我该如何解决这个问题?

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

回答

1

将停止按钮的userInterActionEnabled属性NO和启动当-stop方法被触发时,按钮到YES。然后,当启动-start时,将停止按钮userInterActionEnabled设置为YES,将开始按钮设置为NO

+0

其中是userInterActonEnabled? – user1510082 2012-07-08 18:47:08

+0

这是UIButton的一个属性。像'self.myButton.userInteractionEnabled = NO'; – CodaFi 2012-07-08 19:01:52

1

您应该创建一个私有的布尔变量“isRunning”,就停止点击或开始像时检查:

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

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

    self.isRunning = NO; 
} 

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

+0

我如何创建一个私有布尔变量“isRunning” – user1510082 2012-07-08 18:42:47

+0

将此行添加到@interface(您还可以定义您的IBOutlets,NSTimers等):'BOOL isRunning'。而已 ;-) – tamasgal 2012-07-08 20:23:01