Swift timer method terminates the app early with SIGABRT error

106 Views Asked by At

Below is my code for having a timer change a variable from 0 to 1, which results in a SIGABRT error when the timer tries to fire:

var timerToggle = 0

    let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: false)

    @objc func fireTimer() {
        timerToggle = 1
    }

I know others who've had this problem seem to solve it by placing the timer declaration within the override func viewDidLoad() function but whenever I do that it gives me the following error

"Initialization of immutable value 'timer' was never used; consider replacing with assignment to '_' or removing it."

Any help would be greatly appreciated

3

There are 3 best solutions below

1
lloydTheCoder On

"Initialization of immutable value 'timer' was never used; consider replacing with assignment to '_' or removing it." This is just a warning not an error. You can still go ahead and initialise timer in viewDidLoad.

0
Asperi On

If it is needed to activate once-fired timer in viewDidLoad, it should look somehow like the following

class MyController: UIViewController {
    var timerToggle = 0

    private var timer: Timer?

    deinit {
        timer?.invalidate()
    }

    @objc func fireTimer() {
        timerToggle = 1
        timer = nil
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, 
            selector: #selector(fireTimer), userInfo: nil, repeats: false)
    }
}
1
Joakim Danielson On

If you are not going to access the timer anymore simply add below to viewDidLoad

_ = Timer.scheduledTimer(timeInterval: 5.0, 
                         target: self, 
                         selector: #selector(fireTimer), 
                         userInfo: nil, 
                         repeats: false)