错误 EXC_BAD_INSTRUCTION - 如何设置 timeInterval 方法?

Error EXC_BAD_INSTRUCTION - How to set the timeInterval method?

我求助于您的知识,因为我是编程初学者。我想通过 Playground 实例化一个计时器。我的计时器是 - 我认为 - 正确配置(isValid 和 TimeInterval),游乐场设置也是如此但是当我想将消息发送到它的目标时我有下面的错误消息。我搜索了 Apple 文档、论坛和书籍,但我没有逃脱。对不起。非常感谢您的帮助。

ERROR MESSAGE

Timer 在您指定的目标上调用选择器。在您的情况下,它试图调用实际上并不存在的 AnyObject.timerFire()timerFire 的实现是一个全局函数,它不是类型的一部分,因此不能使用,因为 Timer 需要一个目标。

选择器需要是暴露给 ObjC 的方法,所以类型需要是 class。

这是一个简单的示例。

import Foundation
import PlaygroundSupport

class Foo {
    @objc func timerFired() {
        print("Timer Fired")
    }
}

let f = Foo()
let timer = Timer.scheduledTimer(timeInterval: 1, target: f, selector: #selector(Foo.timerFired), userInfo: nil, repeats: false)

print("Scheduled Timer")

PlaygroundPage.current.needsIndefiniteExecution = true