I know this can be done by using:
[self performSelector:@selector(myMethod) withObject:nil afterDelay:3.0]
However, the problem is that I want only 1 method call do be done. With this function the calls will stack on top of each other. I want to make a call and if another call is made the first one will be dismissed. Ideas?
To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.
Execute Code After Delay Using asyncAfter() Sometimes, you might hit the requirement to perform some code execution after a delay, and you can do this by using Swift GCD (Grand Central Dispatch) system to execute some code after a set delay.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With