How to stop timer when user goes back to previous view

社会主义新天地 提交于 2019-12-13 00:52:48

问题


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.



来源:https://stackoverflow.com/questions/9257997/how-to-stop-timer-when-user-goes-back-to-previous-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!