Jimmy Chen
Jimmy Chen

Reputation: 23

Thread 1: EXC_BAD_ACCESS with Timer

I'm making an app that involves changing UIImageViews by each second/step from a 4-step countdown timer. I get an Thread 1: EXC_BAD_ACCESS error when my program tries to execute the timer at "timer = Timer.scheduledTimer(withTimeInterval: delay, repeats: true){(timer) in if i>4":

func startTimer(slider_Value: Float, coin: Int){
    let delay = Double(slider_Value/5)
    var i = 1
    timer = Timer.scheduledTimer(withTimeInterval: delay, repeats: true){(timer) in
        if i>4{
            timer.invalidate()
        }else{
            switch(i){
            case 1:
                self.updateImages(UIImage(named: "P1Timer1"), UIImage(named: "P2Timer1"))
            case 2:
                self.updateImages(UIImage(named: "P1Timer2"), UIImage(named: "P2Timer2"))
            case 3:
                self.updateImages(UIImage(named: "Timer3"), UIImage(named: "Timer3"))
            case 4:
                self.logo.image = UIImage(named: "Timer4_Logo")
            default:
                self.updateImages(UIImage(named: "Timer0"), UIImage(named: "Timer0"))
                self.logo.image = UIImage(named: "SwipeIsh_Logo")
            }

            i = i+1
        }
    }

Anybody have any idea why this occurs? It just seems weird, and it's occuring in thread 1 (which is the main thread I assume, currently taking Hardware systems right now so I am not an expert on memory)

Here is a screenshot of the crash/debugger

Upvotes: 2

Views: 548

Answers (1)

cora
cora

Reputation: 2102

timer = Timer.scheduledTimer(withTimeInterval: delay, repeats: true){(timer) in

I am guessing that you call startTimer() more than one time. The problem is that every time you call this function you are replacing a timer object that is running with a new one without first invalidating it. You need to add timer.invalidate() just before you create a new one.

if i>4 {
     timer.invalidate()
}

this check will never be true. Every time you call this function, i is reset to 1.

Upvotes: 2

Related Questions