views:

145

answers:

3

Hi, 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?

A: 

You need to actually initialise the TimerCountSeconds and DecreaseTimer members in initialise. Assuming you're control flow is:

...
myObject = [[MyObject alloc] initialize];
...
[myObject touchesBegan:...]
...
[myObject touchesEnded:...]
...

Then when you call initialize TimerCountSeconds has not been initialised, so you're logically doing

[<random pointer> isValid]

Which will crash. Similarly DecreaseTimer is invalid the first time you call touchesBegan.

In your initialise method you will need to actually initialise everything, before you attempt to use anything.

You also appear to be leaking timers (touchesBegin invalidates the timer but does not release it)

olliej
If these are instance variables, they are not "random pointers" — they're nil.
Chuck
+1  A: 

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.

Chuck
when will it be deallocated? so when do I have to retain it?
esanits
It will be deallocated when the runloop decides it can be deallocated. If you want to keep it around, you should retain it when you store it somewhere, as with any other object.
Chuck
okay I think I understood ;) I retained it after the initialisation... now it does not crash any more:) is that correct?
esanits
+3  A: 

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.

Shaggy Frog