48474

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

Question:

This question already has an answer here:

<ul><li> <a href="/questions/36962854/swift-wants-argument-of-selector-to-be-exposed-to-objective-c" dir="ltr" rel="nofollow">Swift wants argument of #selector to be exposed to Objective-C</a> <span class="question-originals-answer-count"> 3 answers </span> </li> </ul>

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!

Answer1:

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:

<ul><li>Mark only the onTick() method with @objc (as Matt already said).</li> <li>Make the Cronometer class a subclass of NSObject.</li> <li>

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() } </li> </ul>

Answer2:

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

Recommend

  • Notifications causing no dealloc to be called
  • JSON validation
  • How to Pass information Back in iOS when reversing a Gesture Recognizer using Swift?
  • Swipe Buttons in IOS 9 Remote Notification - Work when app in background not when app out of memory
  • Chrome identity api to get profile info
  • Help with SimpleCursorAdapter and Listview
  • Stored data can't access in Yii
  • How do js animations work?
  • SharePoint timer job add list items, but does not trigger the associated workflow
  • EJB @Schedule issue
  • powershell: script to start a program with parameters?
  • NSTimer and updating UI
  • GDB skips over my code!
  • Custom Nav Title offset ios 11
  • get all processes in parallel
  • Deleting a widget from QTableView
  • Receive mouse move even cursor is outside control
  • multidatatrigger with multibinding in ControlTemplate.Triggers
  • Is there a parser equivalent of 'fragment' marking in ANTLR4?
  • Faster Way To Simultaneously Iterate Over Rolling Window Of Two Or More Numpy Arrays?
  • How Get arguments value using inline assembly in C without Glibc?
  • How to make R's read_csv2() recognise the text characters properly
  • Build Successful but not running on simulator
  • Implementation of State Monad
  • How VBA declared Volatility works
  • QLPreviewController hide print button in ios6
  • How do I pass the string value parameter of the selected list item from an auto-populated dropdown l
  • Functions in global context
  • Reading JSON from a file using C++ REST SDK (Casablanca)
  • Update CALayer sublayers immediately
  • How to handle AllServersUnavailable Exception
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • sending mail using smtp is too slow
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Busy indicator not showing up in wpf window [duplicate]
  • Sorting a 2D array using the second column C++
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • java string with new operator and a literal