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

标签 swift timer

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

相关文章:

swift - 如何在 Swift 中 OpalImagePicker 的 didfinish 方法中将 PHAsset 类型转换为 URL?

ios - Firebase:由 FIRServerValue.timestamp() 创建的下载时间戳与在线版本略有不同

swift - 确定 View 是否到达 UIScrollView 的顶部

ios - Admob GADBannerView,当 UINavgiationController 存在时不显示

python - 有没有办法阻止计时器蠕变?

Javascript 计时器在页面中使用多次

Javascript如何重新启动计时器

使用 SQL 的 Java Swing 计时器

excel - 如何在 vba excel 中执行 Do Event 计时器,同时仍然能够更改工作表中的值?

ios - 随机数语句不适用于我的 toInt 文本字段输入