Eric
Eric

Reputation: 4061

Delay part of iPhone method

I have a method that takes several params, I need to delay a portion of that method. I DO NOT want to split it into several methods and use [self performSelectorAfterDelay] because the delay requires params already in that method. I need something like the following

-(void)someMethod{
.....

delay {

     more code but not a separate self method
}
... finish method
}

Upvotes: 1

Views: 82

Answers (2)

Richard J. Ross III
Richard J. Ross III

Reputation: 55583

The dispatch_after function seems to line up with what you need:

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
    // this code is going to be executed, on the main queue (or thread) after 2.0 seconds.
});

Of course, the time is configureable, and it's a bit confusing to read at first, but once you get used to how blocks work in conjunction with objective-c code, you should be good to go.

One word of caution:

NEVER, NEVER, NEVER! Block the main thread of an iPhone app using sleep(). Just don't do it!

Upvotes: 3

A-Live
A-Live

Reputation: 8944

Looks like an overkill.

-(void)someMethod{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        NSLog(@"Start code");
        dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
        dispatch_sync(backgroundQueue, ^{

            sleep(5);
            // delayed code
            NSLog(@"Delayed code");
        });

        dispatch_sync(backgroundQueue, ^{

            // finishing code
            NSLog(@"Finishing code");
        });
    });

}

backgroundQueue might be user at external dispatch call. It looks really bad though :)

Upvotes: 1

Related Questions