NSTimer doesn't stop with invalidate

Sergey92zp picture Sergey92zp · Sep 11, 2013 · Viewed 7.4k times · Source

I add timer like this

tim=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(repeatTim) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:tim forMode:NSDefaultRunLoopMode];

tim it is NSTimer property of my class.

Then i stop it on button click like

[[fbt tim] invalidate];
[fbt setTim:nil];

fbt it is instance of my class.

if i call only invalidate then it doesn't stop, but if i set it to nil then i got EXC_BREAKPOINT

here code of repeatTim method in selector

AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
[appDelegate.wbv stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"intal()"]];

I tried to call init and invalidate in

dispatch_async(dispatch_get_main_queue(), ^{})

it also doesn't stop timer.

Answer

Abiola picture Abiola · Apr 10, 2016

You have more than one timer running . Try this:

-(void)startTimer{
    [self.myTimer invalidate]; // kill old timer
    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
}

-(void)stopTimer{
    [self.myTimer invalidate];  
    self.myTimer=nil; //set pointer to nil 
}