2010-05-17 48 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