2013-04-22 56 views
3

我有一個應用程序,我需要在每1或2秒後調用實例方法。現在,如果我把在延遲後執行選擇器只調用一次

[self performSelector:@selector(getMatchListWS) withObject:nil afterDelay:1.0]; 
在viewDidLoad中

:或viewWillAppear中:,該方法getMatchListWS稱爲視圖出現或只加載一次。但即使當用戶在視圖中時,我也需要不斷調用該方法,而視圖不會消失或卸載。那麼,我可以添加performSelector方法的正確位置或委託方法是什麼,以便每秒調用一次,而無需一次又一次卸載視圖。我是否需要在後臺或主線程中執行某些操作?提前致謝!!

回答

11

這將是這樣的:

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(getMatchListWS:) userInfo:nil repeats:YES]; 

把它放在你viewDidLoad,所以你不要有被解僱的多個事件的問題。如果將它放在viewWillAppearviewDidAppear上,並且您正在推送或顯示modalViewController,則可能會發生這種情況。

+4

如果你想它**只重複一次**,它是**重複:否**。從文檔:'重複 如果是,計時器會重複計劃自己,直到無效。如果否,計時器在火災後將失效。「 – Peres 2013-04-22 08:20:51

7

Jacky Boy的回答將完成您的工作。另一種解決方案(如果你是熱衷於使用performSelector法)是添加在同一行中的方法定義,像這樣

-(void) getMatchListWS { 
//Get Match List here 

[self performSelector:@selector(getMatchListWS) withObject:nil afterDelay:1.0]; 
} 

注意:您仍然應該調用該方法,一旦視圖加載時。

+0

必須以這種方式聲明? - (void)getMatchListWS:(NSTimer *)dt {}並用這種方式調用? [self performSelector:@selector(getMatchListWS :) withObject:nil afterDelay:1.0]; – 2015-05-22 07:46:41

1

你只是在延遲你的電話。那會做什麼,是延遲1秒後調用你的方法。你需要做的是設置定時器在特定的時間間隔後重復調用你的方法。

//create an instance of NSTimer class 
NSTimer *timer; 

//set the timer to perform selector (getMatchListWS:) repeatedly 
timer= [NSTimer timerWithTimeInterval:1.0 
             target:self 
             selector:@selector(getMatchListWS:) 
             userInfo:nil 
             repeats:YES];