Releasing an NSTimer iPhone?

2019-04-16 12:48发布

I have an NSTimer declared in my .h and in the viewDidLoad of the /m I have the code:

timer = [NSTimer scheduledTimerWithTimeInterval:kComplexTimer target:self selector:@selector (main) userInfo:nil repeats:YES];

I also have [timer release]; in my dealloc.

However when I exit the view and return to it, the timer has not in fact released, it has doubles in speed! How do I solve this & what am I doing wrong???

Thanks

4条回答
戒情不戒烟
2楼-- · 2019-04-16 13:31

Nice Answer , but good to check whether the time is nil or not to avoid unwanted exception..

if( timer ! = nil )
{
  [timer invalidate];
  timer = nil;
}

Thank you...

查看更多
我想做一个坏孩纸
3楼-- · 2019-04-16 13:32

you don't need to release it as you have not retained it - as a rule. all you need to do is just call [timer invalidate]; which will stop your timer.

查看更多
别忘想泡老子
4楼-- · 2019-04-16 13:32

You must not call release on a object that it not be created by "new", "alloc", "retain", "copy".

In this case, you had created a Timer by scheduledTimerWithTimeInterval method, So you must not call release method but call [timer invalidate] to stop the timer.

查看更多
等我变得足够好
5楼-- · 2019-04-16 13:54
[timer invalidate];
timer = nil;

The second line is important if you want to reset the NSTimer

查看更多
登录 后发表回答