NSTimer 没有停止

发布于 2024-09-24 08:05:16 字数 632 浏览 6 评论 0原文

我有一个带有 NSTimer *myTimer; 变量的类。在某些时候我这样做:

myTimer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(doStuff) userInfo:nil repeats: YES]; 

此外,我有一个方法:

- (void)doStuff
{
  if(myTimer)
  {
    //do stuff
  }
}

并且当类通过以下方式释放时我停止计时器:

- (void)dealloc
{ 
 if (myTimer) { //if myTimer==nil it already has been stopped in the same way
  [myTimer invalidate];
  myTimer = nil;
 }
}

现在,问题是,当我释放类时,计时器会一直持续下去并触发事件。我做错了什么吗?似乎 dealloc 方法从未被调用,否则 myTimer 将为 nil,即使选择器被触发,它也不会进入 if(myTimer)

I have a Class with a NSTimer *myTimer; variable. At some point I do:

myTimer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(doStuff) userInfo:nil repeats: YES]; 

further, I have a method:

- (void)doStuff
{
  if(myTimer)
  {
    //do stuff
  }
}

and I stop my timer when the class is released through:

- (void)dealloc
{ 
 if (myTimer) { //if myTimer==nil it already has been stopped in the same way
  [myTimer invalidate];
  myTimer = nil;
 }
}

Now, the problem is that when I release the class the timer goes on and on and on firing the event anyway. Am I doing something wrong? It seems the dealloc method is never called, otherwise myTimer would be nil and even if the selector is fired it would not go into the if(myTimer)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

流星番茄 2024-10-01 08:05:16

这永远不会起作用,因为计时器会保留其目标,这意味着在您使计时器无效之后之前,您的dealloc方法将永远不会被调用。

有关详细信息,请参阅 NSTimer 文档和这篇关于 "危险的可可呼叫"

This will never work, because timers retain their target, which means your dealloc method will never get invoked until after you've invalidated the timer.

For more info, see the NSTimer documentation and this blog post on "Dangerous Cocoa Calls"

緦唸λ蓇 2024-10-01 08:05:16

您是否尝试过可用的方便的调试器工具?如果在 dealloc 方法中设置断点会发生什么?此外,您应该发布更多有关您的创作的背景信息。您是否有可能多次创建计时器,从而替换原始计时器(但不会使其无效)并将其留在那里随意触发?

Have you tried the handy debugger tools at your disposal? What happens if you set a breakpoint in your dealloc method? Also, you should post more context around your creation. Is it possible you're creating the timer more than once, thereby replacing the original (but not invalidating it) and leaving it out there to fire at will?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文