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

2019-02-12 16:13发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

 [objTimer retain];

Then it will not crash any time. Use this after initializing the timer so it will work fine....



回答4:

You need to set the timer in main thread. NSTimer will not be fired in background thread.

  • Objc:

    dispatch_async(dispatch_get_main_queue(), ^{
       _timer = [NSTimer scheduledTimerWithTimeInterval:delay target:self selector:@selector(YOUR_METHOD) userInfo:nil repeats:YES];
    });
    
  • Swift:

    dispatch_async(dispatch_get_main_queue()) {
       timer = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: "YOUR_METHOD", userInfo: nil, repeats: true)
    }
    


回答5:

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)