【问题标题】:How to stop an NSTimer?如何停止 NSTimer?
【发布时间】:2015-12-08 00:37:59
【问题描述】:

我有一个 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;
}

我在viewWillDisappear中调用了stopTimer方法

- (void) stopTimer
{
    [timer invalidate];
    timer = nil;
}

PS:我在this question中尝试了user1045302的答案,但没有奏效:

How to stop NSTimer

【问题讨论】:

  • timer 是如何声明的?它是您班级的@property,一个实例变量吗?如果您在stopTimer 的开头放置一个断点,它甚至会被调用吗?此时timer 的值是多少?
  • 当你回到viewcontroller那个时候你可以调用[self stoptimer];
  • 你怎么知道计时器没有停止?
  • 从主线程调用stopTimerdispatch_async(dispatch_get_main_queue(), ^{ [self stopTimer]; });
  • @Cyrille : timer 在我的视图控制器中声明如下: NSTimer *timer;

标签: ios objective-c nstimer


【解决方案1】:

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

由于该方法在设置新计时器之前不会使现有计时器无效,因此您实际上有多个计时器同时滴答作响。

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

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

【讨论】:

  • 这似乎是最合乎逻辑的解释。
  • 是的……这在逻辑上是最好的解释
猜你喜欢
  • 2011-03-31
  • 1970-01-01
  • 2013-01-30
  • 2012-08-16
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
相关资源
最近更新 更多