如何杀死NSTimer的同一个实例

时间:2013-07-17 10:08:50

标签: ios6 nstimer

当我退出控制器时,我想用我的NSTimer做一些事情,这样我就不会在viewDidDisappear中使NSTimer无效

    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(stopWatch)
                                                userInfo:nil
                                                 repeats:YES];

- (void)stopWatch
{
// Do something
NSLog(@"stopWatch");
}

-(void)viewDidDisappear:(BOOL)animated {
// Do not invalidate NSTimer here;
}

退出此控制器后,我回到此控制器并

- (void)viewDidLoad
{
[self.timer invalidate];
    self.timer = nil;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(stopWatch)
                                                userInfo:nil
                                                 repeats:YES] ;
}

所以我有2个NSTimer在同一时间运行

当我制作新的NSTimer时,我怎么能使之前的NSTimer无效?

祝你好运

2 个答案:

答案 0 :(得分:1)

目前还不是很清楚问题究竟是什么,但是如果你想要一个持久计时器,那么如果旧计时器存在,我就不会创建一个新计时器:

- (void)viewDidLoad
{
   if (self.timer == nil)
   {
       self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                     target:self
                                                   selector:@selector(stopWatch)
                                                   userInfo:nil
                                                    repeats:YES];
   }

   ...
}

答案 1 :(得分:1)

存储对它的引用并使用:

if([timer isValid]){
    [timer invalidate];
}

或者为了您的目的:

if(![timer isValid]){
    //create timer
}