Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer crashes, when I call [Timer isValid] or [Timer invalidate]

I have two NSTimers in my iPhone app. DecreaseTimer works fine, but TimerCountSeconds crashes when I call [timerCountSeconds isValid] or [timerCountSeconds invalidate]. They are used like this:

-(id)initialize { //Gets called, when the app launches and when a UIButton is pressed
 if ([timerCountSeconds isValid]) {
  [timerCountSeconds invalidate];
 } 
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //Gets called, when you begin touching the screen
 //....
 if ([decreaseTimer isValid]) {
   [decreaseTimer invalidate];
  }
 timerCountSeconds = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(runTimer) userInfo:nil repeats:YES];
 //....
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {//Gets called, when you stop touching the screen(not if you press the UIButton for -(id)initialize)
 //...
 decreaseTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(decrease) userInfo:nil repeats:YES];
 //...
}
-(void)comept3 { //Gets calles when you rubbed the screen a bit
    if ([timerCountSeconds isValid]) {
    [timerCountSeconds invalidate];
    }
}

What did I do wrong? Can you please help me?

like image 816
esanits Avatar asked Sep 11 '10 19:09

esanits


2 Answers

You should set an NSTimer object to nil after you invalidate it, since the invalidate method call also does a release (as per the Apple docs). If you don't, calling a method on it like isValid could cause your crash.

like image 125
Shaggy Frog Avatar answered Sep 20 '22 05:09

Shaggy Frog


Most likely the timer stored in that variable has already been deallocated. You need to retain it if you want to keep it around for an arbitrarily long time.

like image 26
Chuck Avatar answered Sep 19 '22 05:09

Chuck