NSTimer时间戳时间间隔问题

发布于 2024-09-03 09:51:31 字数 422 浏览 0 评论 0原文

我有以下代码:

[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerCount:) userInfo:nil repeats:YES];

-(void)timerCount:(NSTimer *)timer
{
    NSTimeInterval dt = [timer timeInterval];
    // do something
}

我得到的 NSTimeInterval 将为 0.5,这是我放在cheduledTimerWithInterval 上的时间间隔,这意味着timerCount 将每 0.5 秒调用一次。

但我现在有一些像时间戳这样的东西,我想知道 NSTimer 是否每次都会精确地在 0.5 秒内调用timerCount 方法。

I have the following code:

[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerCount:) userInfo:nil repeats:YES];

-(void)timerCount:(NSTimer *)timer
{
    NSTimeInterval dt = [timer timeInterval];
    // do something
}

The NSTimeInterval I got will be 0.5, the time interval I've put on scheduledTimerWithInterval, this means the timerCount will be called each 0.5 seconds.

But I now that there are some stuff as timeStamps, and I want to know if the NSTimer will call the timerCount method in PRECISELY 0.5 seconds each time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

っ左 2024-09-10 09:51:31

在主线程上使用 NSTimer 不会得到这个结果,因为计时器仅由事件循环调用。

如果您需要最大精度,只需创建一个具有自己的消息循环的线程并在那里安排计时器。

You won't get that using NSTimer on main thread as the timer is only called by event loop.

If you need maximal precision just create a thread with it's own message loop and schedule the timer there.

并安 2024-09-10 09:51:31
 aTimer = [NSTimer timerWithTimeInterval:(1.0) target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];

        NSRunLoop *runner = [NSRunLoop currentRunLoop];
        [runner addTimer:aTimer forMode: NSDefaultRunLoopMode];


- (void)timerFired:(NSTimer*)theTimer
 {

    if(condition)
    { 
        //timer terminated
        [theTimer isinValid];
}

}

 aTimer = [NSTimer timerWithTimeInterval:(1.0) target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];

        NSRunLoop *runner = [NSRunLoop currentRunLoop];
        [runner addTimer:aTimer forMode: NSDefaultRunLoopMode];


- (void)timerFired:(NSTimer*)theTimer
 {

    if(condition)
    { 
        //timer terminated
        [theTimer isinValid];
}

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文