本文介绍了如何在 Objective-C 中编写计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 NSTimer 制作秒表.
I am trying to make a stop watch with NSTimer.
我给出了以下代码:
nst_Timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(showTime) userInfo:nil repeats:NO];
而且它不是以毫秒为单位工作的.需要超过 1 毫秒.
and it is not working in milliseconds. It takes more than 1 millisecond.
推荐答案
不要那样使用 NSTimer
.NSTimer 通常用于在某个时间间隔触发选择器.它的精度不高,不适合您想做的事情.
Don't use NSTimer
that way. NSTimer is normally used to fire a selector at some time interval. It isn't high precision and isn't suited to what you want to do.
你想要的是一个高分辨率计时器类(使用NSDate
):
What you want is a High resolution timer class (using 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
定时器.h:
#import <Foundation/Foundation.h>
@interface Timer : NSObject {
NSDate *start;
NSDate *end;
}
- (void) startTimer;
- (void) stopTimer;
- (double) timeElapsedInSeconds;
- (double) timeElapsedInMilliseconds;
- (double) timeElapsedInMinutes;
@end
定时器.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
这篇关于如何在 Objective-C 中编写计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!