Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How initialize a Timer inside a custom class in Swift? [duplicate]

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!

like image 593
Gerson Montenegro Avatar asked Oct 12 '25 21:10

Gerson Montenegro


2 Answers

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()
    }
    
like image 118
Martin R Avatar answered Oct 15 '25 11:10

Martin R


Declare @objc func onTick() and all will be well.

like image 25
matt Avatar answered Oct 15 '25 10:10

matt