简体   繁体   English

NSTimer 有时只触发?

[英]NSTimer only fires sometimes?

Im running into an issue where my timer is randomly not working.我遇到了一个问题,我的计时器随机不工作。 I can literally STOP the app and rebuild it without changing any code.我可以在不更改任何代码的情况下停止应用程序并重建它。 It works sometimes, and sometimes does not?它有时有效,有时无效? When I say "sometimes" I am talking about per app session.当我说“有时”时,我指的是每个应用程序 session。 If it starts up, it will remain running.如果它启动,它将保持运行。 But it is not running every app session.但它并没有运行每个应用程序 session。 I am seeing the same thing when using both code blocks below.使用下面的两个代码块时,我看到了同样的事情。

//Code1:
//I tried this block of code after reading it might be related to how I am interacting with my UIElements while the timer is running in the background.
NSRunLoop *runloop = [NSRunLoop currentRunLoop];
syncWithServerTimer = [NSTimer timerWithTimeInterval:15 target:self selector:@selector(syncWithServer) userInfo:nil repeats:YES];
[runloop addTimer:syncWithServerTimer forMode:NSRunLoopCommonModes];
[runloop addTimer:syncWithServerTimer forMode:UITrackingRunLoopMode];

//Code2:
syncWithServerTimer = [[NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(syncWithServer) userInfo:nil repeats:YES] retain];

Again, I tried both of these and they both work MOST of the time, but not ALL of the time.同样,我尝试了这两种方法,它们大部分时间都有效,但并非所有时间都有效。 What might be the issue?可能是什么问题? I am not prematurely releasing or invalidating.我不会过早地释放或无效。

So I guess its best to fire your timers on your Main Thread.所以我想最好在你的主线程上触发你的计时器。 Seems to work everytime I do it now.似乎我现在每次都这样做。

[self performSelectorOnMainThread:@selector(startTimer) withObject:nil waitUntilDone:NO];

the problem you are seeing (judging by your answer) is that the timer is destroyed with the run loop .您看到的问题(根据您的回答判断)是计时器被run loop 破坏了 if you schedule/add a timer on the run loop, the run loop will not run until all timers are exhausted.如果您在运行循环上安排/添加计时器,则在所有计时器用尽之前,运行循环将不会运行。

if your timer should have the lifetime of the main thread or you cannot guarantee that the run loop will still be around, then add it to the main thread (although strictly, that is also not a guarantee that the timer will fire since the main run loop may exit).如果你的定时器应该有主线程的生命周期,或者你不能保证运行循环仍然存在,那么将它添加到主线程(虽然严格来说,这也不能保证定时器会在主运行后触发循环可能会退出)。

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

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