Asi Givati Asi Givati - 4 months ago 22
iOS Question

Pass a Swift function to NSTimer

I have some function inside another function. in function1 i want to use NSTimer to call func2 after some time like this:

func myFunc1()
{
NSTimer.scheduledTimerWithTimeInterval(1, target: ??, selector:#selector(myFunc2()), userInfo: nil, repeats: false)
func myFunc2()
{
// do something...
}
}


What is the right "target" value that i should pass there? is it even possible?

Answer

The simple answer here is that you can't pass a function to NSTimer because it is an Objective-C based class, which requires a target and a selector.

Instead of doing it though that approach, please consider:

Generic Approach

You can add this class, and reuse it anytime:

class TimerInvocation: NSObject {

    var callback: () -> ()

    init(callback: () -> () {
        self.callback = callback
    }

    func invoke() {
         callback()
    }
}

With this class, you can simply do this now:

let invocation = TimerInvocation {
    /* invocation code here */
}

NSTimer.scheduledTimerWithTimeInterval(1, target: invocation, selector:#selector(TimerInvocation.invoke), userInfo: nil, repeats: false)

You don't have to worry about retaining the invocation variable since it is retained by NSTimer