2011-03-23 50 views
2

我正在開發我的第一個iPhone應用程序。我必須每隔x秒更新一次設備速度的標籤。我創建了我自己的CLController,我可以獲得設備速度,但我不知道是否必須使用NSTimer來更新我的標籤。我該怎麼做?每x秒更新一次速度標籤

回答

4

你可以安排這樣

NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:YOUR_INTERVAL 
         target:self 
         selector:@selector(updateLabel) 
         userInfo:nil 
         repeats:YES]; 

現在下面的方法計時器將調用每YOUR_INTERVAL(單位:秒)期間

- (void) updateLabel { 
    myLabel.text = @"updated text"; 
} 

要停止你可以調用無效計時器在計時器對象上。所以你可能想把計時器保存爲一個成員變量,這樣你就可以在任何地方訪問它。

[timer invalidate]; 
+1

您還需要通過將計時器添加到MainRunLoop'[[NSRunLoop mainRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];' – 2014-02-18 17:38:30

2

你是對的,你必須使用NSTimer。 您將在x秒後調用一個方法並更新標籤。

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

-(void)updateLabel 
{ 
    // update your label 
} 
+0

不要忘記將計時器添加到runloop,否則它不會執行任何操作。 – DarkDust 2011-03-23 11:03:08

+0

謝謝!我可以在NSTimer選擇器中使用參數方法嗎? – 2011-03-23 11:04:55