1
votes

When I start my code I run into the console error

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

the code is the following

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)
    }
}

Also here's a picture of the full error message I am receiving Error Message

1

1 Answers

0
votes

When you use a default value like that, self is not yet fully initialized. Use an implicitly unwrapped optional and move the call into viewDidLoad:

var timer: Timer!

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

This assumes that you do not need the timer before the view controller finishes loading from nib, which should be most of the time.