Releasing an NSTimer iPhone?

2019-04-16 13:14发布

问题:

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

回答1:

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...



回答2:

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.



回答3:

[timer invalidate];
timer = nil;

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



回答4:

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.