I need a timer so I used this code:
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(generalKnowledge.method), userInfo: nil, repeats: true)
But I do not understand the #selector
. I tried multiple times but it doesn't work.
selector() is where you'd add in the function that you want it to call every timeInterval you set. In your example it's every second.
Do bare in mind that in Swift 4 and above, you need to add @objc
before a function if you want to call it in a selector like so:
@objc func handleEverySecond() {
print("Hello world!")
}
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(handleEverySecond), userInfo: nil, repeats: true)
A selector is essentially a message that is sent to an object. It was mostly used in objective-C and Swift has tried to move away from it. However, there are still some objective-C APIs that use it, including the timer one.
This is why selectors must be marked as @objc
since it needs to be exposed in order to be seen.
So when you pass a selector to the timer, you're telling it to send this message to the class when it fires.
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(action), userInfo: nil, repeats: true)
@objc func action() {
print("timer fired")
}
Also, it's important to remember that you need to keep a reference to the timer outside of the scope of the function.