Objective C recursive calls

I try to constantly check the readings from the accelerometer before the camera takes a picture. I have a function that takes a picture, and when I start this function, I check if the accelerometer readings are too high. If so, I would like to call the function again to check if acceleration is stopped.

- (void)takePicture { if (accelerating == YES) { [self takePicture]; } else { // Code that takes picture } } 

I assume that the problem I am facing is a function that is called recursively too many times, and I get "EXC_BAD_ACCESS (code = 2)". How can I fix this recursive call problem?

+4
source share
2 answers

A call of [self takePicture] , which ultimately will retry, which is useless and wasteful, because you do not even give your application time to get additional accelerometers. The accelerating value will probably never change before the stack ends.

What you probably want to do here is a method called part of a second later, for example.

 [self performSelector: @selector(takePicture) withObject:nil afterDelay: 0.01]; return; 

This will cause the loop to call your method again after 10 milliseconds (0.01 seconds).

+8
source

A potential best way to implement this would be to override the installer to speed up something like this:

 - (void)setAccelerating:(BOOL)accelerating { _accelerating = accelerating; if (accelerating) // maybe some more conditions, but you get the idea [self takePicture]; } 
+3
source

All Articles