I have a label in which I want to show the system time. And I want my label to be synchronized with it, i.e. The label will always be displayed at the same time as the time displayed in the status bar.
I set the label text to system time using this snippet:
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "hh:mm"
label.text = formatter.stringFromDate(date)
But I do not know when to run this code. I thought I could run it every minute, but this does not always work. Consider this:
The user starts the application at the system time 08:00:30, this code starts. The time indicated on the status bar and the time indicated on my label are the same: 08:00
At system time 08:01:00, the time displayed in the status bar changes to 08:01. But since 1 minute has not passed since the application was launched, the text of the shortcut is still 08:00.
That's why I said that doing it every minute does not always work.
I also thought to use NSTimerto run this code every second or millisecond. But is it too excessive and cause performance problems?
Is there a “right” way to do this?
source
share