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

时间:2018-09-02 14:10:34

标签: swift selector nstimer

启动代码时,我遇到控制台错误

  

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[_ SwiftValue计数器]:无法识别的选择器已发送到实例

代码如下

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

1 个答案:

答案 0 :(得分:0)

使用类似这样的默认值时,self尚未完全初始化。使用一个隐式展开的可选内容,并将调用移至viewDidLoad

var timer: Timer!

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

这假定您在视图控制器完成从笔尖的加载之前不需要timer,这应该是大多数时间。