带有选择器的定时器方法应该有一个参数:定时器本身。因此,您的代码应该看起来像这样:1
Timer.scheduledTimer(timeInterval: 1.1,
target: self,
selector: #selector(self.adjustmentBestSongBpmHeartRate(_:),
userInfo: nil,
repeats: false)
@objc func adjustmentBestSongBpmHeartRate(_ timer: Timer) {
print("frr")
}
请注意,如果您的应用仅在 iOS >= 10 上运行,您可以使用采用块来调用而不是目标/选择器的新方法。更干净,更安全:
class func scheduledTimer(withTimeInterval interval: TimeInterval,
repeats: Bool,
block: @escaping (Timer) -> Void) -> Timer
该代码如下所示:
timer = Timer.scheduledTimer(withTimeInterval: 1.1,
repeats: false) {
timer in
//Put the code that be called by the timer here.
print("frr")
}
请注意,如果您的计时器块/闭包需要访问您的类中的实例变量,您必须特别注意self。这是此类代码的一个很好的模式:
timer = Timer.scheduledTimer(withTimeInterval: 1.1,
repeats: false) {
//"[weak self]" creates a "capture group" for timer
[weak self] timer in
//Add a guard statement to bail out of the timer code
//if the object has been freed.
guard let strongSelf = self else {
return
}
//Put the code that be called by the timer here.
print(strongSelf.someProperty)
strongSelf.someOtherProperty = someValue
}
编辑(12 月 15 日更新)
1:我应该补充一点,您在选择器中使用的方法必须使用Objective-C动态调度。在 Swift 4 及更高版本中,您引用的各个方法必须使用 @objc 标记。在以前的 Swift 版本中,您还可以使用 @objc 限定符声明定义选择器的整个类,或者您可以使定义选择器的类成为 NSObject 或继承自 NSOBject 的任何类的子类。 (在UIViewController 中定义计时器调用的方法是很常见的,它是NSObject 的子类,因此它曾经“正常工作”。