Max
Max

Reputation: 5942

Swift3 Version of performSelector and cancelPreviousPerformRequestWithTarget

I am trying to invoke a method using some delay ( 0.2 ms ) in swift 3.0 , What i want is to invoke the method with delay for the first time, and when the same method is invoked again it should cancel the previous invocation if already invoked within those 0.2 seconds. I could see objective c had performSelector and cancelPreviousPerformRequestWithTarget but i am not able to find any examples of same for Swift 3.0 , Can any one please help.

Upvotes: 1

Views: 2171

Answers (1)

Vishal Singh
Vishal Singh

Reputation: 4480

Your class has to be subclass of NSObject to get these methods.

    class MyClass: NSObject {

    func performAction(afterDelay delay: TimeInterval)  {
        perform(#selector(MyClass.action), with: self, afterDelay: delay)
    }

    func action(sender: Any?)  {
        print("action called")
    }

    func cancel() {
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(MyClass.action), object: self)
    }
 }

However, if you just need to perform some action fter some delay, you can check GCD methods.

DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { 
            //you action
        }

Upvotes: 2

Related Questions