Search code examples
objective-cinfinite-loopobserver-patternkey-value-observing

How to keep checking a value until it changes without using infinite loop?


My code needs to check on a sensor value until it becomes 1 or the code reach the time out. Hence I am thinking of such an infinite loop.

The sensor is a singleton object that has access to sensor value at real-time. The default value is 0 and I want to monitor for the value change to 1.

for (;;) {
  int sensorVal = [sensor getVal];
  if (sensorVal == 1) break;
  if (timeout) break;
}

But the problem is that I don't want to have an infinite loop in my code. I am wondering if there is a better way to write this in Objective-C?


Solution

  • You can achieve this with using the KVO (key Value observation).

    Observe for changes that you want:

    [sensor addObserver:self forKeyPath:@"val" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];//observing the key in this class
    

    Then use this delegate method:

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
        if([keyPath isEqualToString:@"val"]) {
            /* Do the work here */
        }
    }