如何使用 NSTimer
我在我的应用程序中使用了很多计时器。用于记录时间、移动物体、淡入淡出等。我在不同时间、同一视图中使用相同的计时器来实现多个目的。我应该如何正确声明和无效或释放我的计时器?
Atm 我这样声明计时器:
fadeTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(bortInfo) userInfo:nil repeats:YES];
一旦我不使用它,我就会这样做:
[fadeTimer invalidate];
fadeTimer = nil;
当我离开视图时,每个计时器上的保留计数都是 0。我也应该在释放中释放计时器吗?我的应用程序运行得很好,但有时会崩溃。
我用于更新时间标签的时钟计时器
[[NSRunLoop mainRunLoop] addTimer:clockTimer forMode:NSRunLoopCommonModes];
一旦使时钟计时器无效,我是否需要对此 mainLoop 执行任何操作?
总而言之,请支持我提供一些有关使用计时器的信息。
非常感谢!
乔金
Im using alot of timers in my application. For recording time, moving object, fading etc. I use the same timer for several puposes in the same view at different times. How should I declare and invalidate or release my timers properly?
Atm Im declaring the timers like this:
fadeTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(bortInfo) userInfo:nil repeats:YES];
and as soon as im not using it im doing this:
[fadeTimer invalidate];
fadeTimer = nil;
The retain count when im leaving the view is 0 on every timer. Should i release the timer in the dealloc aswell? My app runs quite good, but from time to time it crashes.
The clockTimer that i use for updating a label with the time uses
[[NSRunLoop mainRunLoop] addTimer:clockTimer forMode:NSRunLoopCommonModes];
Do i need to do anything with this mainLoop once i invalidate the clockTimer?
All in all please support me with some info about working with timers.
Thank you very much!
Joakim
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有正确保留计时器 - 如果您想再次引用它们,您应该保留它们。我会使用头文件中的属性(即)来执行此操作
,并将代码更改为
“这将确保您的计时器由您的对象保留”。否则,您只能希望计时器保持不变并且不会被 iPhone 自动释放。正如你所说,它偶尔会崩溃,这可能就是原因;)
恐怕我对运行循环了解不多,但很困惑为什么你不只使用普通的
NSTimer
来安排事情 - 为什么要费心与运行循环交互呢?You're not retaining your timers properly - if you want to refer to them again you should retain them. I'd do this with a property i.e. in your header file
and change your code to say
This will make sure that your timer is retained by your object. Otherwise you just have to hope that the timer stays around and doesn't get autoreleased by the iPhone. And as you say it's crashing occasionally, this might be the reason ;)
I'm afraid I don't know much about run loop but am confused why your don't just use a normal
NSTimer
to schedule things - why bother interacting with the run loop at all?