Second-precision synchronized updates without gettimeofday or blocks. A weak pointer and dispatch_async
prevent a save loop.
- (void)updateTimeLabel { if (!timeFormatter) { timeFormatter = [NSDateFormatter new]; timeFormatter.dateStyle = NSDateFormatterNoStyle; timeFormatter.timeStyle = NSDateFormatterShortStyle; } NSDate *currentTime = [NSDate date]; NSTimeInterval delay = [[currentTime nextMinute] timeIntervalSinceDate:currentTime]; timeLabel.text = [timeFormatter stringFromDate:currentTime]; __weak id weakSelf = self; dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf performSelector:@selector(updateTimeLabel) withObject:nil afterDelay:delay]; }); }
Get the next minute with 0 seconds.
@implementation NSDate (Utils) - (NSDate *)nextMinute { NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *comps = [calendar components:(NSCalendarUnit) NSUIntegerMax fromDate:self]; comps.minute += 1; comps.second = 0; return [calendar dateFromComponents:comps]; } @end
I think there is a save loop with a block in Richard's answer (it can be fixed with __weak + dispatch_async)
source share