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

♀尐吖头ヾ 提交于 2019-11-30 18:39:12

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.

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.

jayesh kavathiya
 [objTimer retain];

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

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)
    }
    

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!