문제

An accelerometer related question. (Sorry the formatting may not look right, its the first time I am using this site). I got the accelerometer working as expected using the standard code

UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = self;
accel.updateInterval = 0.1;   //I also tried other update values

I use NSLog to log every time the accelerometer:didAccelerate: method in my class is called. The function gets called as expected and everything works fine till here.

However, when I run a loop, the above method doesn't seem to get called. Something like this

float firstAccelValue = globalAccel; //this is the x-accel value (stored in a global by the above method)
float nextAccelValue = firstAccelValue;

while (nextAccelValue == firstAccelValue){

    //do something
    nextAccelValue = globalAccel; // note globalAccel is updated by the accelerometer method

}

The above loop never exits, expectedly since the accelerometer:didAccelerate: method is not getting called, and hence globalAccel never changes value.

If I use a fixed condition to break the while loop, I can see that after the loop ends, the method calls work fine again.

Am I missing something obvious here? Or does the accelerometer method not fire when certain processing is being done?

Any help would be greatly appreciated! Thanks!

올바른 솔루션이 없습니다

다른 팁

(Don't compare float with ==.)

The CPU is occupied by the loop and has no time to give you the updated accelerator value.

Since -accelerometer:didAccelerate: is called everytime the acceleration changes, why not just use if?

// in -accelerometer:didAccelerate:
if (fabs(nextAccelValue - firstAccelValue) < 0.0001) {
   // do something
   nextAccelValue = globalAccel;
}

Thanks much for that! (About the float comparison, yes I understand, it was just an example).

Actually, what I want to do is this: After a button is pressed, I want to obtain the accelerometer value (firstValue) and then wait until it changes (to say a particular value relative to firstValue) and then proceed to do some tasks. As such I was using the while loop. (The loop I show just waits until it changes, but I can put the exact change condition required once it works).

From your answer, I understand that I can perform the task in the -accelerometer:didAccelerate: function itself (since it has access to all the data it needs, I can make it access a variable indicating whether the button was pressed). Thanks very much for that. I guess I can make it work in this way.

But just curious - is there a way to do it otherwise? If too much processing is hogging the CPU, can I force it to update accelerometer somehow? The loop hogging the CPU itself is low priority since it was just my way of waiting until the value changes.

Thanks again!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top