gersonmontenegro gersonmontenegro - 1 year ago 141
iOS Question

How initialize a Timer inside a custom class in Swift?

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)
self.state = !self.state

func onTick(){
self.counter += 1

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)


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!

Answer Source

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 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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download