Objective-C 我的计时器有毫秒数
Having milliseconds in my timer in Objective-C
我正在使用 YouTube 教程制作秒表。问题是我想在我的计时器中使用毫秒,但教程只展示了如何获取秒和分钟。我想让毫秒像分秒一样显示,但我不知道该怎么做。
如何使用此代码获取毫秒数?
@implementation ViewController {
bool start;
NSTimeInterval time;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.display.text = @"0:00";
start = false;
}
- (void) update {
if ( start == false ) {
return;
}
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval elapsedTime = currentTime - time;
int minutes = (int) (elapsedTime / 60.0);
int seconds = (int) (elapsedTime = elapsedTime - (minutes * 60));
self.display.text = [NSString stringWithFormat:@"%u:%02u", minutes, seconds];
[self performSelector:@selector(update) withObject:self afterDelay:0.1];
}
根据文档,"NSTimeInterval is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years."因此您需要做的就是从 elapsedTime
变量中提取毫秒,然后再次格式化您的文本以使其包含毫秒。它可能看起来像这样:
NSInteger time = (NSInteger)elapsedTime;
NSInteger milliseconds = (NSInteger)((elapsedTime % 1) * 1000);
NSInteger seconds = time % 60;
NSInteger minutes = (time / 60) % 60;
//if you wanted hours, you could do that as well
//NSInteger hours = (time / 3600);
self.display.text = [NSString stringWithFormat: "%ld:%ld.%ld", (long)minutes, (long)seconds, (long)milliseconds];
我正在使用 YouTube 教程制作秒表。问题是我想在我的计时器中使用毫秒,但教程只展示了如何获取秒和分钟。我想让毫秒像分秒一样显示,但我不知道该怎么做。
如何使用此代码获取毫秒数?
@implementation ViewController {
bool start;
NSTimeInterval time;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.display.text = @"0:00";
start = false;
}
- (void) update {
if ( start == false ) {
return;
}
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval elapsedTime = currentTime - time;
int minutes = (int) (elapsedTime / 60.0);
int seconds = (int) (elapsedTime = elapsedTime - (minutes * 60));
self.display.text = [NSString stringWithFormat:@"%u:%02u", minutes, seconds];
[self performSelector:@selector(update) withObject:self afterDelay:0.1];
}
根据文档,"NSTimeInterval is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years."因此您需要做的就是从 elapsedTime
变量中提取毫秒,然后再次格式化您的文本以使其包含毫秒。它可能看起来像这样:
NSInteger time = (NSInteger)elapsedTime;
NSInteger milliseconds = (NSInteger)((elapsedTime % 1) * 1000);
NSInteger seconds = time % 60;
NSInteger minutes = (time / 60) % 60;
//if you wanted hours, you could do that as well
//NSInteger hours = (time / 3600);
self.display.text = [NSString stringWithFormat: "%ld:%ld.%ld", (long)minutes, (long)seconds, (long)milliseconds];