Search code examples
iosobjective-ciphonenstimerexc-bad-access

NSTimer crash with EXC_BAD_ACCESS on Iphone when invalidate


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.