How to stop timer when user goes back to previous

2019-07-24 05:57发布

问题:

I have problem with my timer. In my game view in viewDidLoad I have:

sixtySecondTimer = [NSTimer scheduledTimerWithTimeInterval:(1.0/1.0) target:self selector:@selector(changeValue) userInfo:nil repeats:YES];

Next I have changeValue method:

- (void) changeValue {
    timerInt += 1;
    NSLog(@"TimerInt2 = %d", timerInt);
    NSString *string = [NSString stringWithFormat:@"%d", timerInt];
    labelTimer.text = string;
}

And I go to previous view using:

- (IBAction)backView:(id)sender {
    timerInt = 0;
    [self.navigationController popViewControllerAnimated:YES];
}

When I am in previous view in command line I can see:

2012-02-13 10:04:33.393 Colores[1240:707] TimerInt2 = 1
2012-02-13 10:04:34.393 Colores[1240:707] TimerInt2 = 2
2012-02-13 10:04:35.393 Colores[1240:707] TimerInt2 = 3

And when I go to game view in command line I can see this:

2012-02-13 10:04:36.393 Colores[1240:707] TimerInt2 = 4
2012-02-13 10:04:36.508 Colores[1240:707] TimerInt2 = 1
2012-02-13 10:04:37.393 Colores[1240:707] TimerInt2 = 5
2012-02-13 10:04:37.508 Colores[1240:707] TimerInt2 = 2
2012-02-13 10:04:38.393 Colores[1240:707] TimerInt2 = 6
2012-02-13 10:04:38.508 Colores[1240:707] TimerInt2 = 3

Problem is that my timer don't stop and when I go again to game view create "new" variable timerInt... When I go again to previous view and again go to game view then I have three timerInt variable.

How can I fix it?

回答1:

    - (IBAction)backView:(id)sender {
      if ([sixtySecondTimer isValid])
{ 
      [sixtySecondTimer invalidate];
        timerInt = 0;
        [self.navigationController popViewControllerAnimated:YES];
    }

sending invalidate to a timer stops it from firing again



回答2:

You should to invalidate timer before going to the previous controller use this:

 - (IBAction)backView:(id)sender 
{
       if ([sixtySecondTimer isValid])
        {
           [sixtySecondTimer invalidate];
           sixtySecondTimer = nil;
       }
        timerInt = 0;

        [self.navigationController popViewControllerAnimated:YES];
}


回答3:

If you want to stop timer when view is not visible to you, you should invalidateTimer into viewDidDisappear method. If you want to stop timer only when that controller is out of hierarchy, you should invalidateTimer into dealloc method.