Dealloc 调用了两次并在 [super dealloc] 处崩溃
---- 我自己解决了问题,我的评论中更新了信息 ----
我有一个视图控制器,它有一个定期的 NSTimer。当我删除视图控制器时,我调用计时器的无效:
- (void)dealloc
{
NSLog(@"dealloc called");
if ([myTimer isValid]) {
[myTimer invalidate];
}
[super dealloc];
}
我发现了一个意外的行为,[myTimer invalidate]将立即调用我的视图控制器的dealloc。这就是为什么我进行 isValid 检查以避免崩溃。但是 [super dealloc] 将被调用两次并使应用程序崩溃。
因此,我有两个问题:
使计时器无效的正确方法是什么?
为什么定时器的invalidate方法会调用视图控制器的dealloc方法?
谢谢利奥
---- question solved by myself, info updated in my comment ----
I have a view controller which has a periodic NSTimer. I call invalidate of the timer When I remove the view controller:
- (void)dealloc
{
NSLog(@"dealloc called");
if ([myTimer isValid]) {
[myTimer invalidate];
}
[super dealloc];
}
I discovered an unexpected behavior that the [myTimer invalidate] will immediately call my view controller's dealloc. That's why I put the isValid check to avoid crash. But the [super dealloc] will be called twice and crash the app.
Thus, I have two questions:
What's the proper way to invalidate a timer?
Why is the timer's invalidate method call the view controller's dealloc method?
Thanks
Leo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如 CocoaDev: NSTimer 中所述:
As described at CocoaDev: NSTimer:
这听起来像是一些奇怪的行为。是否有任何其他对象保留对视图控制器的引用?
如果没有,一旦定时器被移除,就有可能发生故障。从运行循环中释放后,视图控制器不再引用它(因此被释放)。
That sounds like some odd behaviour. Are there any other objects holding on to a reference to your view controller?
If not, there is a possibility that once the timer is removed & released from the run loop the view controller has nothing referencing it anymore (and so is deallocated).