user1073400
user1073400

Reputation:

How can I use NSTimer with this simple while loop?

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?

Upvotes: 2

Views: 766

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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

}

Upvotes: 3

NSPunk
NSPunk

Reputation: 502

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.

Upvotes: 1

Related Questions