I make a simple cronometer app, but, now I want make it better, and I would like to write a class for the cronometer control:
class Cronometer{
private var counter:Int = 0
private var timer:Timer = Timer()
private var state:Bool = true
func initCronometer(){
if self.state{
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: Selector("onTick"), userInfo: nil, repeats: true)
}else{
self.timer.invalidate()
}
self.state = !self.state
}
func onTick(){
self.counter += 1
print(self.counter)
}
}
But the selector parameter it's not working inside the class with a custom method. I don't want it inside the ViewController, like as I maded before.
I try with
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: Selector(("onTick")), userInfo: nil, repeats: true)
and
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.onTick), userInfo: nil, repeats: true)
...but still not working
So, whats it's the best way to assign a class method as selector in the Timer initializer?
Thanks a lot!
Timer
is an overlay type for the Foundation type NSTimer
,
which uses Objective-C messaging to invoke the timer target.
Therefore the target method must be available for use in Objective-C.
You have the following options:
onTick()
method with @objc
(as Matt already said).Cronometer
class a subclass of NSObject
.On iOS 10/macOS 10.12 you can use the newer block-based timer API:
self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {
_ in self.onTick()
}
Declare @objc func onTick()
and all will be well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With