简体   繁体   English

发行NSTimer iPhone?

[英]Releasing an NSTimer iPhone?

I have an NSTimer declared in my .h and in the viewDidLoad of the /m I have the code: 我在.h和/ m的viewDidLoad中声明了一个NSTimer,我有以下代码:

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

I also have [timer release]; 我也有[定时器发布]; in my dealloc. 在我的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 谢谢

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]; 您所需要做的只是致电[timer invalidate]; which will stop your timer. 这将停止您的计时器。

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

[timer invalidate];
timer = nil;

The second line is important if you want to reset the NSTimer 如果要重置NSTimer ,第二行很重要

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. 在这种情况下,您已经通过ScheduledTimerWithTimeInterval方法创建了一个Timer,因此您不能调用release方法,而必须调用[timer invalidate]来停止计时器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM