Swift 4: Timer Crashing - unrecognized selector sent to instance

无人久伴 提交于 2019-12-02 06:25:58

问题


I'm trying to call an instance of Timer and print "A second has passed" for each second that elapses. I'm following The Complete iOs 11 & Swift Developer Course on Udemy. The instructor does exactly this and his code works, yet mine is crashing.

Here's the code:

var timer: Timer! = Timer()

@IBAction func cameraPressed(_ sender: Any) {
    timer.invalidate()
}

func processTimer() {
    print("A second has passed")
}

override func viewDidLoad() {
    super.viewDidLoad()

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: Selector("processTimer"), userInfo: nil, repeats: true)

It should start the timer upon running the application and then stop it when I press the cameraPressed button. However, it's erroring out with:

unrecognized selector sent to instance...

and

libc++abi.dylib: terminating with uncaught exception of type NSException

I'm new to Swift and the other StackOverflow problems that seem similar to this aren't solving my problem. I've tried changed the "Timer!" optional to "Timer?" and changing "Selector("processTimer")" to "#selector(processTimer)" and I'm still not getting it to work.


回答1:


The callback function processTimer is not correctly declared:

@objc func processTimer() {
   //your code here
}

You need to add the @objc keyword before the function in order to be called in the Timer callback. Also, in general I think is better to use #selector keyword instead.



来源:https://stackoverflow.com/questions/51144072/swift-4-timer-crashing-unrecognized-selector-sent-to-instance

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