gpt4 book ai didi

ios - NSTimer 的最小有效时间间隔是多少?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:22:12 24 4
gpt4 key购买 nike

我想使用 NSTimer 来增加标签上显示的数字。

这是我的代码:

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.numberLabel = [[UILabel alloc]initWithFrame:CGRectMake(90, 90, 90, 30)];
[self.view addSubview:self.numberLabel];


self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(refreshText) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)refreshText{

NSDate *beginDate = [NSDate date];

static NSInteger a = 0;
a ++;

self.numberLabel.text = [NSString stringWithFormat:@"%ld",a];

if (a == 1000) {

NSDate *endDate = [NSDate date];

NSTimeInterval durationTime = [endDate timeIntervalSinceDate:beginDate];
NSTimeInterval intervalTime = self.timer.timeInterval;

NSLog(@"durationTime = %f",durationTime);
NSLog(@"intervalTime = %f",intervalTime);

[self.timer invalidate];
self.timer = nil;
}
}

控制台显示: enter image description here

然后我将定时器的timeInterval从0.01改为0.001,控制台显示: enter image description here

让我疑惑的是为什么timeInterval是0.001时durationTime不是0.0000056。另外,NSTimer的timeInterval有没有最小值可以设置?

最佳答案

NSTimer 的时间段是 NSTimeInterval 类型的值,而这提供了 sub-millisecond precision那对你没有帮助。从NSTimer documentation开始:

Timers work in conjunction with run loops. Run loops maintain strong references to their timers, so you don’t have to maintain your own strong reference to a timer after you have added it to a run loop.

To use a timer effectively, you should be aware of how run loops operate. See Threading Programming Guide for more information.

A timer is not a real-time mechanism. If a timer’s firing time occurs during a long run loop callout or while the run loop is in a mode that isn't monitoring the timer, the timer doesn't fire until the next time the run loop checks the timer. Therefore, the actual time at which a timer fires can be significantly later. See also Timer Tolerance.

因此 NSTimer 的最小时间间隔与运行循环迭代的长度有关。虽然内部优化(如果存在)可以在设置后立即触发计时器,但如果间隔真的很小,一般来说,您将获得的最短时间取决于运行循环迭代的剩余执行时间,其中计时器是集,这对于通用编程来说几乎是不确定的。

如果您真的需要高分辨率计时器(请参阅@bbum 对您的问题的评论),那么您需要研究该主题 - 只需搜索“高分辨率计时 macOS”之类的内容作为起点。

HTH

关于ios - NSTimer 的最小有效时间间隔是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44744939/

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