我正在开发一款需要显示运行时间代码时钟的iPhone/iPad应用程序。我已经让它显示正确的小时、分钟和秒,使用这个代码没有问题:
- (void) viewDidLoad {
// Start the Timer method for here to start it when the view loads.
runTimer = [NSTimer scheduledTimerWithTimeInterval: .01 target: self selector: @selector(updateDisplay) userInfo: nil repeats: YES];
}
- (void)updateDisplay {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *date = [NSDate date];
// Display each hour, minute, second and frame.
[formatter setDateFormat:@"hh"];
[timecodeHourLabel setText:[formatter stringFromDate:date]];
[formatter setDateFormat:@"mm"];
[timecodeMinuteLabel setText:[formatter stringFromDate:date]];
[formatter setDateFormat:@"ss"];
[timecodeSecondLabel setText:[formatter stringFromDate:date]];
}
问题是当我需要每秒显示帧数时。我知道计算1/24 * 1000
可以得到一帧中有多少毫秒。我只是不知道如何使NSDate
和NSTimer
函数与此代码一起工作,并允许它根据需要快速更新UILabel
以运行时间代码。
有什么建议吗?
如果你的计时器以0.01秒的周期运行,那么它的频率是100帧/秒(好吧,最好说它每秒有100个函数调用)。但是,如果你需要显示准确的时间段(因为有时计时器可能会延迟),那么你需要存储以前的通话日期,然后使用
NSDate* new_date = [NSDate date];
double freq = 1.0 / [new_date timeIntervalSinceDate: old_date];
[old_date release];
old_date = [new_date retain];
这里有一个Processing/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)%60), // M (edit: added %60)
floor(ms/1000%60), // S
floor(ms/1000*fps%fps)); // F
}