gpt4 book ai didi

iphone - (NSTimer 释放和失效)的第一步是什么?

转载 作者:行者123 更新时间:2023-12-03 18:49:36 25 4
gpt4 key购买 nike

我可以在 NSTimer 中使用 @selector 发送参数吗?如果我想释放 NSTimer,在 dealloc 中执行以下步骤是否正确?

[timer invalidate];
[timer release];

最佳答案

[timer release] 仅当您“拥有”计时器时才需要调用。来自 Apple's documentation:

Because the run loop maintains the timer, from the perspective of memory management there's typically no need to keep a reference to a timer once you’ve scheduled it. Since the timer is passed as an argument when you specify its method as a selector, you can invalidate a repeating timer when appropriate within that method. In many situations, however, you also want the option of invalidating the timer—perhaps even before it starts. In this case, you do need to keep a reference to the timer, so that you can send it an invalidate message whenever is appropriate. If you create an unscheduled timer (see “Unscheduled Timers”), then you must maintain a strong reference to the timer (in a reference-counted environment, you retain it) so that it is not deallocated before you use it.

这是什么意思?

如果您分配初始化计时器,您还必须释放它,如下所示:

NSTimer * timer = [[NSTimer alloc] initWith...];

NSRunLoop * runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
[timer release];

...
...

[timer invalidate];
timer = nil;

一旦将计时器添加到运行循环中,就没有理由再保留对它的引用,因为运行循环拥有它。在这种情况下,如图所示,您将在将计时器添加到运行循环后立即释放计时器,然后在完成后简单地使其无效。最后一行(将计时器设置为nil)是为了安全起见。对 invalidate 的调用将导致计时器被释放(通过运行循环),因此保留指向它的引用是不安全的。将本地引用设置为 nil 可以保持整洁。

但是,如果您使用如下所示的便捷方法之一创建计时器:

NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval ...];

根本不需要调用[定时器释放]!便捷方法将计时器添加到运行循环中,然后运行循环拥有它,因此您不需要对返回的计时器对象执行任何内存管理。当您不想再使用计时器时,只需使其无效即可:

[timer invalidate];
timer = nil;

或者,如果计时器未设置为重复,则您绝对不会执行任何操作,因为它将在第一次调用后被释放。

关于iphone - (NSTimer 释放和失效)的第一步是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1171393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com