我试图让一个方法每 5 秒调用一次,无论应用程序是否打开或在后台运行,因此在我的 AppDelegate 中,我认为有一个调用方法的计时器是个好主意每 5 秒:
var helloWorldTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(sayHello), userInfo: nil, repeats: true)
@objc func sayHello()
{
print("hello World")
}
但是,我收到此错误:
NSInvalidArgumentException', reason: '-[_SwiftValue sayHello]: unrecognized selector sent to instance
我不完全确定为什么会这样,因为该方法引用正确吗?有谁明白为什么我会收到此错误?
最佳答案
您正在崩溃,因为在 AppDelegate 完全初始化 (target: self
) 之前您无法使用 self
。所以你应该这样初始化计时器:
var helloWorldTimer:Timer?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.helloWorldTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(sayHello), userInfo: nil, repeats: true)
return true
}
引用 Setting a Default Property Value with a Closure or Function 的 Apple 文档:
If you use a closure to initialize a property, remember that the rest of the instance has not yet been initialized at the point that the closure is executed. This means that you cannot access any other property values from within your closure, even if those properties have default values.
此外:
You also cannot use the implicit self property, or call any of the instance’s methods.
关于swift - 无法识别的选择器发送到 AppDelegate 中的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48023668/