0
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBOutlet weak var Time: UILabel!

let everyMinuteTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(ViewController.updateTime), userInfo: nil, repeats: true)

@objc func updateTime() {

    let currentDateTime = Date()

    let formatter = DateFormatter()
    formatter.timeStyle = .medium
    formatter.dateStyle = .long

    let dateTimeString = formatter.string(from: currentDateTime)

    Time.text = dateTimeString
}

I've tried to get this timer to fire to update a time label, but it doesn't seem to fire and keeps the text static.

This is the error I keep getting:

'unrecognized selector sent to instance 0x600000faed90'

pawello2222
  • 46,897
  • 22
  • 145
  • 209

2 Answers2

2

The issue there is that your code should be inside a method. There is no self when you are initialising your timer property. You have two options.

  1. Declare your timer as lazy var

  2. Move your timer declaration to any view controller method usually viewDidLoad.

Note that I would also change your timer interval frequency. 100 times per second is way too much. If you just need to fire your method when the minute changes you can schedule your timer to start at the next even minute and repeat it just once a minute.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
1

The problem is a tricky issue involving the meaning of self. Change

override func viewDidLoad() {
    super.viewDidLoad()
}

let everyMinuteTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(ViewController.updateTime), userInfo: nil, repeats: true)

To

override func viewDidLoad() {
    super.viewDidLoad()
    self.everyMinuteTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(ViewController.updateTime), userInfo: nil, repeats: true)
}

var everyMinuteTimer : Timer!

I know it seems incredible, but this will fix the issue.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    See also https://www.biteinteractive.com/rant-swift-cocoa-target-action/ for an extensive rant. – matt Jan 18 '21 at 19:50