这个 NSTimer dealloc 是否可以接受或者会产生意外的错误?
我复制了我的代码,所以我像这样重构了它:
-(void) dealloc {
[self resetTimer];
[super dealloc];
}
-(void) resetTimer {
if( timer != nil ) {
[timer invalidate];
}
timer = nil;
// set some other value to zero...
}
在 dealloc 方法中调用这个 ResetTimer 方法是否可以接受?否则我最终会在resetTimer中写入相同的4行两次。
I was duplicating my code, so I refactored it like this:
-(void) dealloc {
[self resetTimer];
[super dealloc];
}
-(void) resetTimer {
if( timer != nil ) {
[timer invalidate];
}
timer = nil;
// set some other value to zero...
}
Is it acceptable to call this resetTimer method in the dealloc method? Otherwise I will end up writing the same 4 lines in resetTimer twice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@mackworth 所说:
但是,您没有显示计时器的创建。如果它是这样的:
那么你的对象的dealloc将永远不会被调用。至少,您的代码中并非没有过度发布错误。
计时器保留其目标。因此,如上所述创建的计时器将在您的对象和计时器之间创建一个保留周期。
一种解决方案是当您希望计时器停止时显式调用
resetTimer
(我将其称为invalidateTimer
因为重置意味着您正在重置计时器以继续运行)。另一种方法是不保留计时器并且不在
dealloc
中释放它。看起来有点奇怪,但有时你必须玩这类弱参考游戏。What @mackworth said:
However, you didn't show the timer's creation. If it is something like:
Then your object's
dealloc
will never be invoked anyway. At least, not without an over-release bug in your code.A timer retains its target. Thus, a timer created as above will create a retain cycle between your object and the timer.
One solution is to explicitly call
resetTimer
when you want the timer to stop (I'd call itinvalidateTimer
as reset implies that you are resetting the timer to continue running).Another is to not retain the timer and not release it in
dealloc
. Looks a bit wonky, but sometimes you have to play these kinds of weak reference games.我做了同样的事情,而且对我来说效果很好。 (虽然我确实依赖于 nil 调用,所以它只是:)
I did same thing, and it worked fine for me. (Although I do rely on the nil call, so it's just:)