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.
You need to retain the timer yourself to guarantee that it’s still around after it has fired.
scheduledTimerWithTimeIntervalreturns an autoreleased instance that you don’t own.