gpt4 book ai didi

swift - 无法识别的选择器发送到 AppDelegate 中的实例

转载 作者:可可西里 更新时间:2023-11-01 00:33:45 25 4
gpt4 key购买 nike

我试图让一个方法每 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com