gpt4 book ai didi

iphone - 如何在 Objective-C 中编写计时器?

转载 作者:IT老高 更新时间:2023-10-28 11:47:45 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com