ios – NSTimer不会因无效而停止

我像这样添加计时器
tim=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(repeatTim) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:tim forMode:NSDefaultRunLoopMode];

这是我班级的NSTimer属性.

然后我点击按钮就停止它

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

fbt它是我班级的实例.

如果我只调用invalidate然后它不会停止,但如果我将它设置为nil然后我得到了EXC_BREAKPOINT

这里选择器中的repeatTim方法的代码

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

我试着调用init并使其无效

dispatch_async(dispatch_get_main_queue(),^{})

它也不会停止计时器.

解决方法

阅读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.)

您正在使用已将其从1添加到mainLoop的方法. – 您需要删除此行或使用2.方法创建计时器并保留手动添加.

还要记住,必须从安装了计时器的线程发送无效消息.如果从另一个线程发送此消息,则可能无法从其运行循环中删除与计时器关联的输入源,这可能会阻止线程正常退出.

以上是来客网为你收集整理的ios – NSTimer不会因无效而停止全部内容,希望文章能够帮你解决ios – NSTimer不会因无效而停止所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。