Re: Displaying time
Re: Displaying time
- Subject: Re: Displaying time
- From: Ron Fleckner <email@hidden>
- Date: Sat, 23 Aug 2008 08:15:06 +1000
On 23/08/2008, at 1:18 AM, Michael Ash wrote:
On Fri, Aug 22, 2008 at 8:51 AM, Ron Fleckner
<email@hidden> wrote:
Is there a way to update the time without using an NSTimer? I'd
like my
clock to be synchronised with the menu bar clock. Maybe this
isn't a Cocoa
question. Thanks for your answers.
It's pretty simple. Use a *non* repeating timer. In the timer's action
method, compute the time until the next update. Then set up a new
*non* repeating timer for that time interval. For example, something
like this:
- (void)updateClock:(id)ignore
{
// update your clock based on the current time
NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
double whole = trunc(now);
double fract = now - whole;
double remaining = 1.0 - fract;
[NSTimer scheduledTimerWithTimeInterval:remaining target:self
selector:_cmd userInfo:nil repeats:NO];
}
And then just call this method once on startup to get the ball
rolling. The advantage is that you're only updating once per second,
but your updates still follow extremely closely after the value
updates. And it's self synchronizing, so if some kind of event happens
to interrupt the update cycle (like sleeping the computer, or a huge
burst of disk IO which blocks your app) then it will quickly get back
on schedule once the method does manage to fire.
The same technique can be applied to fractions of a second, or to
minutes, hours, days, etc.
Mike
Wow, cool. I didn't know about _cmd, but found it in the docs in
"The Objective-C Programming Language". Thanks very much. It's a
pity someone had to write my code for me, but I appreciate it anyway.
Ron
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden