如何在这个简单的while循环中使用NSTimer? [英] How can I use NSTimer with this simple while loop?

查看:45
本文介绍了如何在这个简单的while循环中使用NSTimer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个-(void)方法正在执行,并且有一点它进入了while循环,该循环从加速度计要求输入值的那一刻就直接从加速度计获取值

I have a -(void) method being executed and at one point it gets to a while loop that gets values from the accelerometer directly the moment it asks for them

我遍历了有关NSTimer类的文档,但无法理解我在这种情况下使用该对象的确切程度:

I went throughout the documentation regarding the NSTimer class but I couldn't make sense of how exactly I am to use this object in my case :

例如

-(void) play
{
    ......
    ...



    if(accelerationOnYaxis >0 && accelerationOnYaxis < 0.9 )
    {
        startTimer;
    }

    while(accelerationOnYaxis >0 && accelerationOnYaxis < 0.9)
    {
        if(checkTimer >= 300msec)
        {

           printOut_AccelerationStayedBetweenThoseTwoValuesForAtLeast300msecs;
           break_Out_Of_This_Loop;
        }

    }

    stopTimerAndReSetTimerToZero;

    .....
    more code...
    ....
    ...
}

有帮助吗?

推荐答案

您无法使用 NSTimer 进行此操作,因为它需要退出代码才能触发. NSTimer 使用事件循环来决定何时给您回电;如果您的程序将控件保存在 while 循环中,则无法触发计时器,因为永远不会到达用于检查是否触发时间的代码.

You cannot do it with NSTimer, because it needs your code to exit in order to fire. NSTimer uses the event loop to decide when to call you back; if your program holds the control in its while loop, there is no way for the timer to fire, because the code that checks if it's time to fire or not is never reached.

最重要的是,在繁忙的循环中呆了将近半秒会耗尽您的电池.如果您只需要等待 1.4s ,则最好调用 sleepForTimeInterval:,如下所示:

On top of that, staying in a busy loop for nearly a second and a half is going to deplete your battery. If you simply need to wait for 1.4s, you are better off calling sleepForTimeInterval:, like this:

[NSThread sleepForTimeInterval:1.4];

您还可以使用 clock() < time.h> 中进行测量,以测量较短的时间间隔,如下所示:

You can also use clock() from <time.h> to measure short time intervals, like this:

clock_t start = clock();
clock_t end = start + (3*CLOCKS_PER_SEC)/10; // 300 ms == 3/10 s
while(accelerationOnYaxis >0 && accelerationOnYaxis < 0.9)
{
    if(clock() >= end)
    {
       printOut_AccelerationStayedBetweenThoseTwoValuesForAtLeast300msecs;
       break_Out_Of_This_Loop;
    }

}

这篇关于如何在这个简单的while循环中使用NSTimer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆