微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.方法创建计时器并保留手动添加.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐