Timer on swift not working

↘锁芯ラ 提交于 2019-12-25 09:10:07

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/42742540/timer-on-swift-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!