user1510082
user1510082

Reputation: 35

Stopwatch glitches

I made a stopwatch application recently and it had a few glitches.

If I hit the stop button twice in a row, the entire app would crash.

If I hit the start button twice in a row, the timer would run twice as fast and the stop button would stop working.

How do I fix this problem?

Here is the code in my .h file:

    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

and here is my code in the .m file:

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

Upvotes: 1

Views: 396

Answers (2)

tamasgal
tamasgal

Reputation: 26259

You should create a private BOOL variable "isRunning", which is checked when clicked on Stop or Start like:

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

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

    self.isRunning = NO;
}

etc. Also ignoring user interactions is general a good idea (like CodaFi suggested), but only fights the symptoms ;-) You really should do both checks.

Upvotes: 1

CodaFi
CodaFi

Reputation: 43330

Set the stop button's userInterActionEnabled property to NO and the start button's to YES when the -stop method is fired. Then switch and set the stop button's userInterActionEnabled to YES and the start button's to NO when -start is fired.

Upvotes: 1

Related Questions