2012-08-22 16 views
14

我正在處理以5秒爲單位處理設備動作事件和更新界面的應用程序。我想嚮應用程序添加一個指示器,以顯示應用程序運行的總時間。似乎像秒錶一樣的計數器,就像本機iOS時鐘應用程序一樣,是計算應用程序運行時間並將其顯示給用戶的合理方式。向iOS應用程序添加正在運行的countup顯示計時器,如時鐘秒錶?

我不確定的是這種秒錶的技術實現。下面是我在想什麼:

  • ,如果我知道如何界面更新之間的長,我能事件之間加起來秒,並保持幾秒鐘的時間算作一個局部變量。或者,間隔0.5秒的計時器可以提供計數。

  • 如果我知道這個應用程序的開始日期,我可以在本地變量轉換爲日期使用[[NSDate dateWithTimeInterval:(NSTimeInterval) sinceDate:(NSDate *)]

  • 我可以使用一個NSDateFormatter用時短的風格各接口更新到更新的日期轉換使用stringFromDate方法的字符串方法

  • 生成的字符串可以分配給接口中的標籤。

  • 結果是秒錶針對應用程序的每個「滴答」更新。

在我看來,這個實現有點太重,不像秒錶應用程序那樣流暢。是否有更好,更具互動性的方式來計算應用程序運行的時間?也許iOS已經爲此提供了一些東西?

+0

定義「太重」,「不太流暢」和「更具交互性」。你想解決什麼問題? – Jim

+0

太重了,我的意思是說應用程序正在做很多計算,而且我讀過日期操作涉及日期格式化程序或日曆是「昂貴」的操作。我想減少秒錶的每次更新日期計算的開銷 –

回答

22

幾乎什麼@terry劉易斯建議,但有一個算法的調整:

1)安排一個計時器

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES]; 

2)當定時器觸發,獲取當前時間(這是好辦法,不要」 t計數滴答,因爲如果計時器中有擺動,滴答計數會累積錯誤),然後更新UI。另外,NSDateFormatter是一種更簡單,更通用的格式顯示時間的方式。

- (void)timerTick:(NSTimer *)timer { 
    NSDate *now = [NSDate date]; 

    static NSDateFormatter *dateFormatter; 
    if (!dateFormatter) { 
     dateFormatter = [[NSDateFormatter alloc] init]; 
     dateFormatter.dateFormat = @"h:mm:ss a"; // very simple format "8:47:22 AM" 
    } 
    self.myTimerLabel.text = [dateFormatter stringFromDate:now]; 
} 
22

如果您在the iAd sample code from Apple在基本旗幟的項目看起來他們有一個簡單的計時器:

NSTimer *_timer; 
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES]; 

和方法,他們有

- (void)timerTick:(NSTimer *)timer 
{ 
    // Timers are not guaranteed to tick at the nominal rate specified, so this isn't technically accurate. 
    // However, this is just an example to demonstrate how to stop some ongoing activity, so we can live with that inaccuracy. 
    _ticks += 0.1; 
    double seconds = fmod(_ticks, 60.0); 
    double minutes = fmod(trunc(_ticks/60.0), 60.0); 
    double hours = trunc(_ticks/3600.0); 
    self.timerLabel.text = [NSString stringWithFormat:@"%02.0f:%02.0f:%04.1f", hours, minutes, seconds]; 
} 

它只是運行的啓動,很基本的。

+0

如何將計數器重置爲00:00:00? –

+0

適用於iOS的模擬時鐘 https://github.com/Boris-Em/BEMAnalogClock –

相關問題