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

无人久伴 提交于 2019-12-12 10:00:18

问题


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 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()
    }
    



回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!