Search code examples
ios6nstimer

How to kill same instance of NSTimer


I want to do something with my NSTimer when i exit my controller, so that i don't invalidate NSTimer in viewDidDisappear

    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;
}

After exit this controller, i come back this controller and

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

So i have 2 NSTimer run in the same time

How can i invalidate my previous NSTimer when i make a new one?

Best regards


Solution

  • It's not very clear exactly what the issue is, but if you want a persistent timer, then I would simply not create a new one if an old one exists:

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