ios - NSTimer 不会因无效而停止

标签 ios nstimer invalidation

我这样添加定时器

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

tim 它是我类​​级的 NSTimer 属性。

然后我在点击按钮时停止它

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

fbt 它是我的类的实例。

如果我只调用 invalidate 那么它不会停止,但是如果我将它设置为 nil 那么我得到 EXC_BREAKPOINT

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

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

我尝试在

中调用 initinvalidate
dispatch_async(dispatch_get_main_queue(), ^{})

它也不会停止计时器。

最佳答案

您有多个计时器在运行。试试这个:

-(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 
}

关于ios - NSTimer 不会因无效而停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18745175/

相关文章:

ios - 在 iOS 上通过 twitter 登录并在我的服务器上进行身份验证

ios - 从 NSTimer 回到主线程

xcode - 跟踪时间(当应用程序关闭或在后台时)

Android:只有创建 View 层次结构的原始线程在调用 invalidate() 时才能触摸其 View

iphone - (iphone) 重复 : no? 时我需要使计时器无效吗

jsp - session.invalidate() 在 Websphere Application Server 中不起作用

ios - Remove Child From Firebase 快速删除整个节点

ios - 如何正确初始化 UIView 子类中传递的属性?

具有许多不同 View 的 iOS 应用程序

iphone - objective-c : Timer crashes app when turned on a second time