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?
You cannot do it with
NSTimer, because it needs your code to exit in order to fire.NSTimeruses the event loop to decide when to call you back; if your program holds the control in itswhileloop, 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 callingsleepForTimeInterval:, like this:You can also use
clock()from<time.h>to measure short time intervals, like this: