Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel with current time

I have a UILabel that I want to show the current time (HH:mm) (the same time as in the status bar).

How do I update the label to change to the new time? If I schedule an NSTimer with an interval of 60 seconds, then label could be out of time by up to a minute, if the timer fires just before the system time's minute changes?

Would it be ok to set the timer's interval to 1 second, or will that use more resources than necessary? Or is there another way to make sure the label will stay in sync with the status bar clock (preferably exactly, but 1 second lee way is ok)?

like image 728
Jonathan. Avatar asked Jul 19 '12 18:07

Jonathan.


1 Answers

Dispatch is your friend:

void runBlockEveryMinute(dispatch_block_t block)
{
    block(); // initial block call

    // get the current time
    struct timespec startPopTime;
    gettimeofday((struct timeval *) &startPopTime, NULL);

    // trim the time
    startPopTime.tv_sec -= (startPopTime.tv_sec % 60);
    startPopTime.tv_sec += 60;

    dispatch_time_t time = dispatch_walltime(&startPopTime, 0);

    __block dispatch_block_t afterBlock = ^(void) {
        block();

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 60), dispatch_get_main_queue(), afterBlock);
    };

    dispatch_after(time, dispatch_get_main_queue(), afterBlock); // start the 'timer' going
}

This will synchronize down to the nanosecond and only call when the minute changes. I believe that this is the optimal solution for your situation.

like image 158
Richard J. Ross III Avatar answered Oct 04 '22 21:10

Richard J. Ross III