Ios6 如何杀死同一个NSTimer实例

Ios6 如何杀死同一个NSTimer实例,ios6,nstimer,Ios6,Nstimer,我想在退出控制器时对我的NSTimer执行一些操作,这样我就不会在ViewDidEnglishe中使NSTimer无效 self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(st

我想在退出控制器时对我的NSTimer执行一些操作,这样我就不会在ViewDidEnglishe中使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无效


致以最诚挚的问候

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

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

   ...
}

存储对它的引用并使用:

if([timer isValid]){
    [timer invalidate];
}
或出于您的目的:

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

我不明白;当你使旧的计时器失效时,你怎么能有两个计时器呢?因为0.5秒后,我的“秒表”功能被调用了。不清楚你想要什么。当视图消失时,为什么要激活计时器?如果你已经有一个计时器在运行,为什么还要启动一个新的计时器呢?计时器功能的一些指示可能会有所帮助。我想在离开我的电脑时更新一些东西controller@trojanfoe:在后台为所有控制器执行某些操作的最佳解决方案是什么?