2010-05-17 39 views
1

我非常接近完成我的第一個iphone應用程序,它一直是一種快樂。我試圖使用當前時間通過NSTimer在UILabel上顯示當前時間(NSDate)來添加運行時間碼。 NSDate對我來說工作正常,顯示小時,分鐘,秒,毫秒。但是,而不是毫秒,我需要顯示每秒24幀。使用NSTimer和NSDateFormatter顯示時間碼

問題是我需要每秒的幀數與小時,分鐘和秒同步100%,所以我不能將幀添加到單獨的計時器中。我嘗試過,並使其工作,但幀計時器沒有與日期計時器同步運行。

任何人都可以幫我解決這個問題嗎?有沒有辦法自定義NSDateFormatter,以便我可以有每秒24幀格式的日期計時器?現在我只限於格式化小時,分鐘,秒和毫秒。

這是我現在使用

-(void)runTimer { 
// This starts the timer which fires the displayCount method every 0.01 seconds 
runTimer = [NSTimer scheduledTimerWithTimeInterval: .01 
      target: self 
      selector: @selector(displayCount) 
      userInfo: nil 
       repeats: YES]; 
} 

//This formats the timer using the current date and sets text on UILabels 
- (void)displayCount; { 

NSDateFormatter *formatter = 
[[[NSDateFormatter alloc] init] autorelease]; 
    NSDate *date = [NSDate date]; 

// This will produce a time that looks like "12:15:07:75" using 4 separate labels 
// I could also have this on just one label but for now they are separated 

// This sets the Hour Label and formats it in hours 
[formatter setDateFormat:@"HH"]; 
[timecodeHourLabel setText:[formatter stringFromDate:date]]; 

// This sets the Minute Label and formats it in minutes 
[formatter setDateFormat:@"mm"]; 
[timecodeMinuteLabel setText:[formatter stringFromDate:date]]; 

// This sets the Second Label and formats it in seconds 
[formatter setDateFormat:@"ss"]; 
[timecodeSecondLabel setText:[formatter stringFromDate:date]]; 

//This sets the Frame Label and formats it in milliseconds 
//I need this to be 24 frames per second 
[formatter setDateFormat:@"SS"]; 
[timecodeFrameLabel setText:[formatter stringFromDate:date]]; 

} 

回答

1

我建議您從NSDate提取毫秒的代碼 - 這是在幾秒鐘內,所以部分會給你毫秒。

然後,只需使用明文格式字符串來使用NSString方法stringWithFormat附加值:。

+0

經過一番玩,我仍然不知道如何實現這一點。我已經能夠成功地做你的建議,但似乎我錯過了實際上每秒24幀轉換的一大塊數學。我不需要每秒顯示100毫秒,而是需要顯示每秒鐘通過0-23的數字,並且我需要它與NSTimer完美同步,以便實際完成並在每秒結束時重新啓動。 – 2010-05-18 05:10:05

0

下面是一個處理/ Java等價物,相當簡單地重新調整用途。

String timecodeString(int fps) { 
    float ms = millis(); 
    return String.format("%02d:%02d:%02d+%02d", floor(ms/1000/60/60), // H 
               floor(ms/1000/60),  // M 
               floor(ms/1000%60),  // S 
               floor(ms/1000*fps%fps)); // F 
} 
1

NSFormatter + NSDate的開銷很大。另外,在我看來,NSDate並沒有爲簡單的東西提供「簡單」microtime情況。

Mogga提供一個很好的指針,這裏有一個C/Objective-C的變種:

- (NSString *) formatTimeStamp:(float)seconds { 
    int sec = floor(fmodf(seconds, 60.0f)); 
    return [NSString stringWithFormat:@"%02d:%02d.%02d.%03d", 
         (int)floor(seconds/60/60),   // hours 
         (int)floor(seconds/60),    // minutes 
         (int)sec,       // seconds 
         (int)floor((seconds - sec) * 1000) // milliseconds 
      ]; 
} 

// NOTE: %02d is C style formatting where: 
// % - the usual suspect 
// 02 - target length (pad single digits for padding) 
// d - the usual suspect 

查找有關此格式的詳細信息,請參閱this discussion