2011-08-12 58 views
1

进入我的计时器随机不工作的问题。我可以从字面上停止应用程序并重建它,而无需更改任何代码。它有时有效,有时不会? 当我说“有时”时,我正在讨论每个应用程序会话。如果启动,它将继续运行。但它没有运行每个应用程序会话。 在使用下面的两个代码块时,我看到了同样的情况。NSTimer有时仅会触发?

//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]; 

同样,我想这两个,他们都工作的大部分时间,但不是所有的时间。 可能是什么问题?我不会过早释放或失效。

+0

您在哪种方法中执行计时器初始化(您发布的代码)? – sergio

+0

嗨@sergio它在-viewDidLoad – Louie

+0

没有看到更多的代码,这是不可能的。这两者看起来像插入到-viewDidLoad时会很好地工作。在启动另一个实例之前,您在Xcode中杀死应用程序后可能没有正确等待? –

回答

1

所以我想最好在你的主线上解雇你的定时器! 似乎现在每次我都会工作。

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

你看到(通过你的回答判断)的问题是,计时器被破坏与运行循环。如果您在运行循环中安排/添加计时器,则只有在所有计时器耗尽之后,运行循环才会运行。

如果你的计时器应该有主线程的生命周期,或者你不能保证运行循环仍然在周围,然后将它添加到主线程(尽管严格来说,这也不能保证计时器会触发因为主运行循环可能会退出)。

相关问题