Cancel a timed event in Swift?

前端 未结 7 1945
说谎
说谎 2020-11-27 15:36

I want to run a block of code in 10 seconds from an event, but I want to be able to cancel it so that if something happens before those 10 seconds, the code won\'t run after

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 16:08

    Update for Swift 3.0

    Set Perform Selector

    perform(#selector(foo), with: nil, afterDelay: 2)
    

    foo method will call after 2 seconds

     func foo()
     {
             //do something
     }
    

    To cancel pending method call

     NSObject.cancelPreviousPerformRequests(withTarget: self)
    

提交回复
热议问题