NSTimer 没有停止
我有一个带有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这永远不会起作用,因为计时器会保留其目标,这意味着在您使计时器
无效
之后之前,您的dealloc
方法将永远不会被调用。有关详细信息,请参阅
NSTimer
文档和这篇关于 "危险的可可呼叫"This will never work, because timers retain their target, which means your
dealloc
method will never get invoked until after you'veinvalidated
the timer.For more info, see the
NSTimer
documentation and this blog post on "Dangerous Cocoa Calls"您是否尝试过可用的方便的调试器工具?如果在 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?