Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for a timer or a condition to become true and then process the code? (Wait for a iOS camera to adjust focus)

I want to process some code after some condition checking. First of it is that some variable must be true (I have a Key-Value Observer assigned to it). Second - if that variable hasn't become true for some time (e.g. 5 seconds), then nevermind the variable and just process the code.

I come with an obvious solution, which, I think, is bad: infinite while() loop in another dispatch queue, every time checking the true condition and time passed. And all this code is wrapped in another dispatch queue... well, does not look good for me.

The draft pseudocode of what I want to do:

WHEN (5 seconds are gone || getCurrentDynamicExpr() == true) {
    processStuff();
} 

What's the right and easy way to do this?

EDIT

Seems a lot of confusion here... Got to be more concrete:

I want to capture a camera shot when it's focused, so I want to check AVCaptureDevice's isAdjustingFocus property (I'm using AVCaptureStillImageOutput), and then capture a shot. 5 seconds are for.. well, if it didn't focus then something is wrong, so take the picture anyway.

I'm sorry about a confusion, thought it's something really common..

like image 233
dreamzor Avatar asked Nov 30 '25 11:11

dreamzor


1 Answers

You might consider an NSConditionLock on which you can lockWhenCondition:beforeDate:, or possibly schedule something to occur in five seconds (eg, by NSTimer or dispatch_after) that checks whether the other processing has already begun, the other processing being event triggered and setting a flag.

EDIT:

So, for the record:

const NSInteger kConditionLockWaiting = 0;
const NSInteger kConditionLockShouldProceed = 1;

[...]

conditionLock = [[NSConditionLock alloc] initWithCondition:kConditionLockWaiting];

[...]

dispatch_async(...
^{
    [conditionLock
         lockWhenCondition:kConditionLockShouldProceed
         beforeDate:[[NSDate date] dateByAddingTimeInterval:5.0]];

    // check the return condition to find out whether you timed out
    // or acquired the lock
});

[...]

- (void)observeValueForKeyPath:(NSString *)keyPath
        ofObject:(id)object change:(NSDictionary *)change
        context:(void *)context
{
    if(this is the appropriate property)
    {
        [conditionLock lock];
        [conditionLock unlockWithCondition:kConditionLockShouldProceed];
    }
}
like image 157
Tommy Avatar answered Dec 03 '25 02:12

Tommy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!