问题
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!
回答1:
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:
- Mark only the
onTick()method with@objc(as Matt already said). - Make the
Cronometerclass a subclass ofNSObject. 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() }
回答2:
Declare @objc func onTick() and all will be well.
来源:https://stackoverflow.com/questions/39622721/how-initialize-a-timer-inside-a-custom-class-in-swift