2011-08-12 56 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

你看到(通過你的回答判斷)的問題是,計時器被破壞與運行循環。如果您在運行循環中安排/添加計時器,則只有在所有計時器耗盡之後,運行循環纔會運行。

如果你的計時器應該有主線程的生命週期,或者你不能保證運行循環仍然在周圍,然後將它添加到主線程(儘管嚴格來說,這也不能保證計時器會觸發因爲主運行循環可能會退出)。

相關問題