NSTimer crash with EXC_BAD_ACCESS on Iphone when invalidate
-
22-07-2019 - |
Question
I have setup two timers in my application which both repeats every a few seconds. Everything works fine except when is time to invalidate the timers. When the phone is locked, I want to invalidate those timers and then recreate them when the phone is unlocked.
Im using the notifications to realize when to invalidate/create the timers.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notify_didBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notify_willResigneActive:) name:UIApplicationWillResignActiveNotification object:nil];
This is what the notify_didBecomeActive method contains:
clockTicker = [[NSTimer scheduledTimerWithTimeInterval: 1
target: self
selector: @selector(showActivity)
userInfo: nil
repeats: YES] retain];
alarmTicker = [[NSTimer scheduledTimerWithTimeInterval: CONST_ALARMTIMER
target: self
selector: @selector(checkAndLaunchAlarm)
userInfo: nil
repeats: YES] retain];
This the notify_willResigneActive method contains:
if (alarmTicker) {
[alarmTicker invalidate];
[alarmTicker release];
alarmTicker = NULL;
}
if (clockTicker) {
[clockTicker invalidate];
[clockTicker release];
clockTicker = NULL;
}
The problem is that when I debug this on the second timer invalidate I get the error. The weird thing is that if I switch the orders of the timers (like first invalidate the clockTicker).. I still got the error on the second timer.
What could I be doing wrong?
Thanks, Leonardo
Solution
invalidate releases the timer, no need to release after invalidating, thats why its crashing. But i just noticed that you are retaining the timer...im not sure that this is necessary either.
OTHER TIPS
You just need to set alarmTicker and clockTicker to nil inside the methods that those timers fire and that way when you do your check if (alarmTicker) or if (clockTicker) they'll have the right value.
I'm not sure what setting the timer to NULL does as opposed to setting it to nil, but I know that if you make a call on a nil object, it's a no-op. If you make a call on a NULL object, it think it crashes, though I haven't verified this. This post might help: NULL vs nil in Objective-C