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 show the same time as the time shown in the status bar.
I set the text of the label to the system time using this snippet:
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "hh:mm"
label.text = formatter.stringFromDate(date)
But I don't know when to run this code. I thought I can run it every minute, but that doesn't always work. Consider this:
The user starts the app at system time 08:00:30, the above code is run. The time shown in the status bar and the time shown in my label are the same: 08:00
At system time 08:01:00, the time shown in the status bar changes to 08:01. But since 1 minute has not yet passed since the start of the app, the label's text is still 08:00.
That's why I said doing it every minute doesn't always work.
I also thought of using an NSTimer
to run that code every second or millisecond. But isn't that too excessive and will cause performance issues?
Is there a "proper" way to do this?
You can keep calling your function every minute as you said but at the first time you can run it after 30 seconds (system time was 08:00:30) then continue calling after 1 minute and in that case I think they will be identical
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With