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

KTO*_*TOV 2 timer swift

无论应用程序是打开还是在后台运行,我都试图获得一个每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")
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误:

NSInvalidArgumentException', reason: '-[_SwiftValue sayHello]: unrecognized selector sent to instance 
Run Code Online (Sandbox Code Playgroud)

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

And*_*ini 5

您正在崩溃,因为self在AppDelegate完全初始化(target: 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
}
Run Code Online (Sandbox Code Playgroud)

通过使用闭包或函数设置默认属性值来引用Apple文档:

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

此外:

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