Delay a method call in objective-c

In the Code Snippet Library in Xcode you can find one called GCD: Dispatch After, which looks like this:

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    <#code to be executed on the main queue after delay#>
});

Pretty self-explanatory.


Once the method is executing then there is no way of stopping it.

But you can cancel if it is not fired. You can do something like this

//.... your code
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(myMethod) object:nil];
[self performSelector:@selector(myMethod) withObject:nil afterDelay:3.0];
//.... your code

In this way you can cancel previous perform request only if the myMethod is not being fired.


EDIT: Now that I know that you want to only use the most recent, you could instead use:

[self cancelPreviousPerformRequestsWithTarget:self selector:@selector(myMethod) object:nil];

See this link for more info.

ORIGINAL POST:

You could just have a BOOL that is set to NO when it reaches that section and is then reset to YES after the method is performed.

So, for example, it would look something like:

if (boolVal) {
    boolVal = NO;
    [self performSelector:@selector(myMethod) withObject:nil afterDelay:3.0];
}

then in your myMethod, have:

boolVal = YES;

You should perform this selector in some other thread to avoid stack as you asked. use

[self performSelector:(SEL) onThread:(NSThread *) withObject:(id) waitUntilDone:(BOOL)];

In that selector you can add delay what ever you want. As this process will run in separate thread so will not stop others for the delay