NSTimer doesn't stop with invalidate

风流意气都作罢 提交于 2019-11-28 04:12:21

问题


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.


回答1:


Read documentation for NSTimer:

There are three ways to create a timer:

  1. Use the scheduledTimerWithTimeInterval:invocation:repeats: or scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: class method to create the timer and schedule it on the current run loop in the default mode.

  2. Use the timerWithTimeInterval:invocation:repeats: or timerWithTimeInterval:target:selector:userInfo:repeats: class method to create the timer object without scheduling it on a run loop. (After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode: method of the corresponding NSRunLoop object.)

  3. Allocate the timer and initialize it using the initWithFireDate:interval:target:selector:userInfo:repeats: method. (After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode: method of the corresponding NSRunLoop object.)

You are using method which already adds it to mainLoop from 1. - you need to remove this line or create a timer with 2. approach and leave manual adding.

Also remember that you must send invalidate message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.




回答2:


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 
}


来源:https://stackoverflow.com/questions/18745175/nstimer-doesnt-stop-with-invalidate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!