作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试使用 NSTimer 制作秒表。
我给出了以下代码:
nst_Timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(showTime) userInfo:nil repeats:NO];
它无法在几毫秒内工作。这需要超过 1 毫秒。
最佳答案
不要那样使用 NSTimer
。 NSTimer 通常用于在某个时间间隔触发选择器。它的精度不高,不适合你想做的事情。
你想要的是一个高分辨率计时器类(使用NSDate
):
输出:
Total time was: 0.002027 milliseconds
Total time was: 0.000002 seconds
Total time was: 0.000000 minutes
主要:
Timer *timer = [[Timer alloc] init];
[timer startTimer];
// Do some work
[timer stopTimer];
NSLog(@"Total time was: %lf milliseconds", [timer timeElapsedInMilliseconds]);
NSLog(@"Total time was: %lf seconds", [timer timeElapsedInSeconds]);
NSLog(@"Total time was: %lf minutes", [timer timeElapsedInMinutes]);
编辑:为 -timeElapsedInMilliseconds
和 -timeElapsedInMinutes
Timer.h:
#import <Foundation/Foundation.h>
@interface Timer : NSObject {
NSDate *start;
NSDate *end;
}
- (void) startTimer;
- (void) stopTimer;
- (double) timeElapsedInSeconds;
- (double) timeElapsedInMilliseconds;
- (double) timeElapsedInMinutes;
@end
Timer.m
#import "Timer.h"
@implementation Timer
- (id) init {
self = [super init];
if (self != nil) {
start = nil;
end = nil;
}
return self;
}
- (void) startTimer {
start = [NSDate date];
}
- (void) stopTimer {
end = [NSDate date];
}
- (double) timeElapsedInSeconds {
return [end timeIntervalSinceDate:start];
}
- (double) timeElapsedInMilliseconds {
return [self timeElapsedInSeconds] * 1000.0f;
}
- (double) timeElapsedInMinutes {
return [self timeElapsedInSeconds] / 60.0f;
}
@end
关于iphone - 如何在 Objective-C 中编写计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3519562/
我是一名优秀的程序员,十分优秀!