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

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...