0

I have a problem with timer setting.

The code I wrote for it is:

import UIKit class ViewController: UIViewController { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: Selector(("updateTimer")), userInfo: nil, repeats: true) } func updateTimer(){ label.text = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: DateFormatter.Style.short, timeStyle: DateFormatter.Style.short) } } 

I run the app, and instead of timer I get an error of type Thread. Something like:

"Thread 1: signal SIGBART"

What could be the problem?

1
  • Can you post the stack trace of your crash log? That might help point out the issue Commented Jun 15, 2018 at 17:10

2 Answers 2

1

Things will work better if you replace Selector(("updateTimer")) with #selector(updateTimer).

Then you'll be told you need to add @objc to your updateTimer function.

Unrelated but don't use NSDate.

Here's your fixed code:

class ViewController: UIViewController { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) } @objc func updateTimer() { label.text = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short) } } 
Sign up to request clarification or add additional context in comments.

2 Comments

As a side note, you should keep a reference to the timer so you can invalidate it when you are done with it.
It also will be better if you hold scheduled Timer instance in a variable in order to invalidate timer when the vc deinits (to avoid Bad Access exception)
0

Change your code to this:

import UIKit class ViewController: UIViewController { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) } @objc func updateTimer(){ label.text = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: DateFormatter.Style.short, timeStyle: DateFormatter.Style.short) } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.