0

I am programming with Swift 2.1.

I have a function in class:

private func doTask(button: UIButton) {...}

I want to call this function after 2 seconds, I know I could use :

NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "doTask", userInfo: nil, repeats: false)

But, in the selector part, how can I pass the parameter button: UIButton to doTask?

Leem.fin
  • 40,781
  • 83
  • 202
  • 354

1 Answers1

0

Timers can only call methods that take a timer as their parameter. Selectors are just names of methods; they can't carry data. You have to make a new method that takes a timer and calls doTask. You can pass data in the userInfo parameter if you want to configure things, but you still need an extra method.

This kind of timer probably isn't what you want anyway. Just use dispatch_after.

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    doTask(button)
}

You can see Matt's implementation of delay() that makes this a little easier to use.

Community
  • 1
  • 1
Rob Napier
  • 286,113
  • 34
  • 456
  • 610