JoseIgnacio
JoseIgnacio

Reputation: 74

Timer on swift not working

I have a function working with a button:

@IBAction func btnSiguiente(_ sender: Any) {
    if indexImagenes == imagenes.count {
        indexImagenes = 0
    }
    escaparate.image = NSImage(named: imagenes[indexImagenes])
    indexImagenes += 1
}

I want to make it work with a Timer:

 var playTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(autoplay), userInfo: nil, repeats: true)


func autoplay() {
    if indexImagenes == imagenes.count {
        indexImagenes = 0
    }
    escaparate.image = NSImage(named: imagenes[indexImagenes])
    indexImagenes += 1
}

But I get this in console:
[_SwiftValue autoplay]: unrecognized selector sent to instance 0x6080000451c0

Upvotes: 0

Views: 1044

Answers (1)

J.beenie
J.beenie

Reputation: 831

To fix this, initialize the timer once the instance of the class your are in is fully initialized.

So just give the var playTimer a default value as follows:

var playerTimer:Timer? = nil

Then initialize the timer in some function that gets called once 'self' is fully initialized (like viewDidLoad() for example, assuming this code is in a viewController):

override func viewDidLoad()
{
    super.viewDidLoad()
    playerTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(autoplay), userInfo: nil, repeats: true)
}

Essentially just make sure 'self' is fully initialized before you send it a selector to perform.

Upvotes: 3

Related Questions