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

问题描述 投票:2回答:1

无论应用程序是打开还是在后台运行,我都试图获得一个每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 

我不完全确定为什么因为该方法被正确引用?有谁知道我为什么会收到这个错误?

swift timer
1个回答
5
投票

你崩溃是因为在AppDelegate完全初始化之前你不能使用selftarget: 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文档:

如果使用闭包来初始化属性,请记住在执行闭包时尚未初始化实例的其余部分。这意味着您无法从闭包中访问任何其他属性值,即使这些属性具有默认值。

此外:

您也不能使用隐式self属性,也不能调用任何实例的方法。

© www.soinside.com 2019 - 2024. All rights reserved.