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

StackOverflow https://stackoverflow.com/questions/18114164

  •  23-06-2022
  •  | 
  •  

Question

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;
}
Was it helpful?

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);
}];

OTHER TIPS

Don't block or poll.

  • set a timer for 5 seconds

  • if whatever condition is met, check the condition after 5 seconds and do the fail case or success case if necessary

  • if you want to take action immediately on completion, then use any of the various "perform thing on main thread" constructs to do so (also setting the condition to let the timer firing no that the task was done)

  • you can invalidate the timer to keep it from firing at all, if you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top