如何阻止NSTimer?

sam*_*ray 3 objective-c nstimer ios

我有一个NSTimer,我希望在我离开时停止vViewVontroller:

计时器是我调用的方法viewWillAppear:

- (void) myMehtod
{
    //timer = [[NSTimer alloc] init];
    // appel de la methode chaque 10 secondes.
     timer  =  [NSTimer scheduledTimerWithTimeInterval:10.0f
                                     target:self selector:@selector(AnotherMethod) userInfo:nil repeats:YES];
    //self.timerUsed = timer;
}
Run Code Online (Sandbox Code Playgroud)

我将方法称为stopTimer viewWillDisappear

- (void) stopTimer
{
    [timer invalidate];
    timer = nil;
}
Run Code Online (Sandbox Code Playgroud)

PS:我在这个问题上尝试了user1045302的答案,但它不起作用:

如何阻止NSTimer

Nik*_*uhe 5

问题的根源可能是myMehtod被调用两次或更多次.

由于该方法在设置新计时器之前不会使现有计时器无效,因此您实际上有多个计时器同时进行计时.

修复很简单:在设置新计时器之前使旧计时器无效:

- (void)myMehtod
{
    [timer invalidate];
    timer = [NSTimer scheduledTimerWithTimeInterval:10.0f
                                             target:self
                                           selector:@selector(anotherMethod)
                                           userInfo:nil
                                            repeats:YES];
}
Run Code Online (Sandbox Code Playgroud)