Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay a method call in objective-c

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?

like image 892
Michael Avatar asked Mar 19 '13 10:03

Michael


People also ask

How do you delay a call method?

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.

How to call a method with delay in Swift?

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.


2 Answers

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.

like image 109
Inder Kumar Rathore Avatar answered Oct 21 '22 22:10

Inder Kumar Rathore


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.

like image 21
Alejandro Benito-Santos Avatar answered Oct 21 '22 23:10

Alejandro Benito-Santos