On Jul 27, 2013, at 9:57 PM, Andy Lee <[email protected]> wrote:
> I'm trying again, this time creating a new NSTimer each time as suggested by 
> Scott Ribe.  Will let it run a while and see if I notice any drift.

Looks pretty solid after several minutes -- as I would expect.  To repeat 
Scott's suggestion:

> Personally, I'd probably just do a non-repeating timer, set to fire at the 
> next second roll-over. Alloc'ing, scheduling and releasing 1 timer per second 
> is not a lot of overhead.

I didn't take my own suggestion to add .001 and it worked fine, though for all 
I know it might have a problem once every 10,000 times the app is run.

I stole Rick Mann's code and replaced trunc() with round().

--Andy

==========

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self _resetTimer];
}

- (void)_resetTimer
{
    CFAbsoluteTime fireDateAbs = round(CFAbsoluteTimeGetCurrent() + 0.5);  // 
Round to the next second
    NSDate *fireDate = [NSDate 
dateWithTimeIntervalSinceReferenceDate:fireDateAbs];

    [[self timer] invalidate];
    [self setTimer:[[NSTimer alloc] initWithFireDate:fireDate
                                            interval:1.0
                                              target:self
                                            selector:@selector(_timerDidFire:)
                                            userInfo:nil
                                             repeats:NO]];
    [[NSRunLoop currentRunLoop] addTimer:[self timer] 
forMode:NSRunLoopCommonModes];
}

- (void)_timerDidFire:(NSTimer *)theTimer
{
    [self _updateTimeDisplay];
    [self _resetTimer];
}

- (void)_updateTimeDisplay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
    [dateFormatter setDateStyle:NSDateFormatterNoStyle];

    NSString *timeString = [dateFormatter stringFromDate:[NSDate date]];

    [[self textField] setStringValue:timeString];
}

@end


_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to