How can I use NSTimer with this simple while loop?

好久不见. 提交于 2019-12-07 21:41:57

问题


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

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 :

e.g.

-(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...
    ....
    ...
}

Any help?


回答1:


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.

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];

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;
    }

}



回答2:


NSTimer works a little different than you want. What you need is a counter for your timer, to get how many times it looped. If your counter gets on 14 (if it's an integer), you can invalidate it.

//start timer
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1
        target:self
        selector:@selector(play:)
        userInfo:nil
        repeats:YES];

//stop timer
[timer invalidate];

You can create your function without that while.

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


    counter++; //declare it in your header

    if(counter < 14){
        x++; //your integer needs to be declared in your header to keep it's value
    } else {
        [timer invalidate];
    }

    useValueofX;
}

Take a look at the documentation.



来源:https://stackoverflow.com/questions/11728570/how-can-i-use-nstimer-with-this-simple-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!