这个 NSTimer dealloc 是否可以接受或者会产生意外的错误?

发布于 2024-10-18 06:05:00 字数 331 浏览 0 评论 0原文

我复制了我的代码,所以我像这样重构了它:

-(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 技术交流群。

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

发布评论

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

评论(2

挖个坑埋了你 2024-10-25 06:05:00

@mackworth 所说:

-(void) resetTimer {
   [timer invalidate];
    timer = nil;
}

但是,您没有显示计时器的创建。如果它是这样的:

timer = [[NSTimer scheduledTimerWithTimeInterval: 42 target:self ...] retain];

那么你的对象的dealloc将永远不会被调用。至少,您的代码中并非没有过度发布错误。

计时器保留其目标。因此,如上所述创建的计时器将在您的对象和计时器之间创建一个保留周期。

一种解决方案是当您希望计时器停止时显式调用 resetTimer (我将其称为 invalidateTimer 因为重置意味着您正在重置计时器以继续运行)。

另一种方法是保留计时器并且dealloc中释放它。看起来有点奇怪,但有时你必须玩这类弱参考游戏。

What @mackworth said:

-(void) resetTimer {
   [timer invalidate];
    timer = nil;
}

However, you didn't show the timer's creation. If it is something like:

timer = [[NSTimer scheduledTimerWithTimeInterval: 42 target:self ...] retain];

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 it invalidateTimer 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.

爺獨霸怡葒院 2024-10-25 06:05:00

我做了同样的事情,而且对我来说效果很好。 (虽然我确实依赖于 nil 调用,所以它只是:)

-(void) resetTimer {
   [timer invalidate];
    timer = nil;
}

I did same thing, and it worked fine for me. (Although I do rely on the nil call, so it's just:)

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