Search code examples
objective-ckif

Objective c - Run block of code for X seconds but return immediately if condition satisfies


So the situation is I need to run the code for 5 seconds but if I match the condition then want it to immediately return back. I am doing this in KIF test steps and I don't want this to block my applications main thread.

Sample pseudo Code -

+ (BOOL) isVerified:(NSString*)label;
{
     if(<condition match>)
        return YES;
    else if(X seconds not passed)
       <make sure m running this function for X seconds>
    else // X seconds passed now..
       return NO;
}

Solution

  • If you don't want to block the main thread in the case that NO should be returned after 5 sec delay, then structure that API asynchronously.

    typedef void(^CCFVerificationCallbackBlock)(BOOL verified);
    
    @interface CCFVerifier : NSObject
    
    - (void)verifyLabel:(NSString *)label withCallbackBlock:(CCFVerificationCallbackBlock)block;
    
    @end
    
    static const int64_t ReturnDelay = 5.0 * NSEC_PER_SEC;
    
    @implementation CCFVerifier
    
    - (void)verifyLabel:(NSString *)label withCallbackBlock:(CCFVerificationCallbackBlock)block {
        NSParameterAssert(block);
        if( [label isEqualToString:@"moo"] )
            block(YES);
        else {
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, ReturnDelay);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                block(NO);
            });
        }
    }
    @end
    

    To use:

    _verifier = [[CCFVerifier alloc] init];
        [_verifier verifyLabel:@"foo" withCallbackBlock:^(BOOL verified) {
         NSLog(@"verification result: %d",verified);
    }];