将 Swift 函数传递给 NSTimer
Pass a Swift function to NSTimer
我在另一个函数中有一些函数。在 function1 中,我想像这样在一段时间后使用 NSTimer 调用 func2:
func myFunc1()
{
NSTimer.scheduledTimerWithTimeInterval(1, target: ??, selector:#selector(myFunc2()), userInfo: nil, repeats: false)
func myFunc2()
{
// do something...
}
}
我应该传递给那里的正确 "target" 值是多少?有可能吗?
如果您的目标是 iOS 10 之前的版本,则不能将函数传递给 NSTimer
,因为当时没有引入 API 来支持闭包回调。
iOS 10 及以后方法
// swift 2.x users should still use NSTimer instead
Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { timer in
// ...
}
通用方法
您可以添加此 class,并随时重复使用:
final class TimerInvocation: NSObject {
var callback: () -> ()
init(callback: @escaping () -> ()) {
self.callback = callback
}
func invoke() {
callback()
}
}
extension Timer {
static func scheduleTimer(timeInterval: TimeInterval, repeats: Bool, invocation: TimerInvocation) {
Timer.scheduledTimer(
timeInterval: timeInterval,
target: invocation,
selector: #selector(TimerInvocation.invoke(timer:)),
userInfo: nil,
repeats: repeats)
}
}
有了这个 class,您现在可以简单地这样做:
let invocation = TimerInvocation {
/* invocation code here */
}
NSTimer.scheduledTimerWithTimeInterval(1, target: invocation, selector:#selector(TimerInvocation.invoke), userInfo: nil, repeats: false)
您不必担心保留 invocation
变量,因为它由 NSTimer
保留
在Swift3中,新的Timer
有一个采用闭包的工厂方法:
Timer.scheduledTimer(withTimeInterval: TimeInterval, repeats: Bool, block: (Timer) -> Void)
在你的情况下,你可以使用尾随闭包语法这样调用它:
Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
// do something
}
注意: 这仅适用于 iOS 10 或更新版本。
我在另一个函数中有一些函数。在 function1 中,我想像这样在一段时间后使用 NSTimer 调用 func2:
func myFunc1()
{
NSTimer.scheduledTimerWithTimeInterval(1, target: ??, selector:#selector(myFunc2()), userInfo: nil, repeats: false)
func myFunc2()
{
// do something...
}
}
我应该传递给那里的正确 "target" 值是多少?有可能吗?
如果您的目标是 iOS 10 之前的版本,则不能将函数传递给 NSTimer
,因为当时没有引入 API 来支持闭包回调。
iOS 10 及以后方法
// swift 2.x users should still use NSTimer instead
Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { timer in
// ...
}
通用方法
您可以添加此 class,并随时重复使用:
final class TimerInvocation: NSObject {
var callback: () -> ()
init(callback: @escaping () -> ()) {
self.callback = callback
}
func invoke() {
callback()
}
}
extension Timer {
static func scheduleTimer(timeInterval: TimeInterval, repeats: Bool, invocation: TimerInvocation) {
Timer.scheduledTimer(
timeInterval: timeInterval,
target: invocation,
selector: #selector(TimerInvocation.invoke(timer:)),
userInfo: nil,
repeats: repeats)
}
}
有了这个 class,您现在可以简单地这样做:
let invocation = TimerInvocation {
/* invocation code here */
}
NSTimer.scheduledTimerWithTimeInterval(1, target: invocation, selector:#selector(TimerInvocation.invoke), userInfo: nil, repeats: false)
您不必担心保留 invocation
变量,因为它由 NSTimer
在Swift3中,新的Timer
有一个采用闭包的工厂方法:
Timer.scheduledTimer(withTimeInterval: TimeInterval, repeats: Bool, block: (Timer) -> Void)
在你的情况下,你可以使用尾随闭包语法这样调用它:
Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
// do something
}
注意: 这仅适用于 iOS 10 或更新版本。