使用 NSTimer 时发送到实例的无法识别的选择器

unrecognized selector sent to instance when using NSTimer

当我开始我的代码时,我 运行 进入控制台错误

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue counter]: unrecognized selector sent to instance

代码如下

class Status: UIViewController {
    @IBOutlet var health: UIProgressView!
    @IBOutlet var happiness: UIProgressView!
    @IBOutlet var energy: UIProgressView!
    @IBOutlet var hygiene: UIProgressView!
    @IBOutlet var pain: UIProgressView!
    @IBOutlet var hunger: UIProgressView!

    var total:Double = 1

    @objc func counter() {
       total -= 0.05
    }

    let timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(counter), userInfo: nil, repeats:true)

    override func viewDidLoad() {
        super.viewDidLoad()

        hunger.setProgress(Float(total), animated: true)
        happiness.setProgress(Float(total), animated: true)
        energy.setProgress(Float(total), animated: true)
        hygiene.setProgress(Float(total), animated: true)
        pain.setProgress(Float(total), animated: true)
        health.setProgress(Float(total), animated: true)
    }
}

这里还有一张我收到的完整错误消息的图片 Error Message

当您使用这样的默认值时,self 尚未完全初始化。使用隐式展开的可选并将调用移至 viewDidLoad:

var timer: Timer!

override func viewDidLoad() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(counter), userInfo: nil, repeats:true)
}

这假定您不需要 timer 在视图控制器从 nib 完成加载之前,这应该是大部分时间。