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.
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