如何检查NSTimer是否已经自动失效?
我在创建不重复的 NSTimer 时遇到问题。
创建了一个新实例
timer = [NSTimerchedTimerWithTimeInterval:3.0 target:selfselector:@selector(updateSystems) userInfo:nil Repeats:NO];
想象一下,我在代码中的某处
。如果我按下 iPhone 上的主页按钮,我的应用程序将进入后台状态,并且计时器仍然存在,只是暂停。因此,在我的 applicationDidEnterBackground
方法中,我说
if(timer.isValid == YES)
{
[timer invalidate];
timer = nil;
}
如果我在计时器完成后按下主页按钮,就会出现问题。然后计时器已经被释放,导致尝试访问 isValid 时崩溃。
尝试
if(timer != nil)
{
[timer invalidate];
timer = nil;
}
会导致同样的崩溃,因为 Cocoa 的自动失效似乎没有将计时器设置为 nil。
如何检查定时器是否自动失效?
谢谢。
注意:我需要这样做的原因是因为我正在向 Web 服务发送请求,一旦请求成功(或失败),我就会启动一个计时器,一旦触发它就会发送一个新请求。如果我没有在计时器完成之前使计时器失效,则会创建多个计时器(因为我正在 applicationDidBecomeActive
上发出新请求),从而在只需要一个计时器时发出多个请求。
I have a problem when creating an NSTimer without repeat.
Imagine I create a new instance
timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(updateSystems) userInfo:nil repeats:NO];
somewhere in my code.
If I press the home button on the Iphone, my app will enter background state, and the timer will still be around, just be paused. So in my applicationDidEnterBackground
method I say
if(timer.isValid == YES)
{
[timer invalidate];
timer = nil;
}
The problem arises if I press the Home button after the timer has completed. Then the timer has been released, resulting in a crash when trying to access isValid.
Trying
if(timer != nil)
{
[timer invalidate];
timer = nil;
}
results in the same crash, since Cocoa's auto-invalidation doesn't seem to set the timer to nil
.
How is it possible to check wether the timer has auto-invalidated or not?
Thank you.
NOTE: The reason I need to do this is because I'm sending a request to a web service, once the request has been successful (or a failure) I start a timer that will send a new request once it gets fired. If I don't invalidate the timer before it's finished, several timers will be created (since I'm making a new request on applicationDidBecomeActive
) making multiple request when only one is needed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要自己保留计时器,以保证它在触发后仍然存在。
scheduledTimerWithTimeInterval
返回一个不属于您的自动释放实例。You need to retain the timer yourself to guarantee that it's still around after it has fired.
scheduledTimerWithTimeInterval
returns an autoreleased instance that you don't own.