Re: Keeping NSTimeInterval updated with current time
Re: Keeping NSTimeInterval updated with current time
- Subject: Re: Keeping NSTimeInterval updated with current time
- From: Ken Thomases <email@hidden>
- Date: Mon, 2 Nov 2009 21:03:16 -0600
On Nov 2, 2009, at 7:10 PM, Graham Cox wrote:
On 03/11/2009, at 10:10 AM, PCWiz wrote:
What I want to do is around every 5 minutes, update the
timeInterval to be consistent with the current time. The problem is
that I need to do this update for a large number of instances of
the object. One way I could think to do this would be to enumerate
through the array containing the objects every 5 minutes and just
set the timeInterval property. But is there a more efficient way to
do this?
But, maybe a better answer is to consider why you are doing this. If
you have a bunch of objects that need to know the current time (to
the nearest five minutes) why not just have them grab that time at
the moment when they need to know it. If they are just sitting there
they don't need to be updated - only when one of them is called into
play and needs to do some calculation with the time does that time
need to be updated, at which point it should grab it for itself. If
rounding off the time to the last 5-minute interval is a problem
(e.g. every object must have the exact same value), you could do
that every 5 minutes and cache the result somewhere where all the
other objects can grab it as needed.
This type of lazy evaluation is by far the better way to code a
problem like this - do the minimum work necessary, and never push
state to objects that don't need it *NOW*.
Agreed, in general, but there may be a reason to have the objects
updated at each 5-minute tick: if there are KVO observers of the
timeInterval property and you want them to know it's been updated
(e.g. it's bound to a view in the GUI).
One possible approach is for each of your objects to have a reference
to a common clock object. The clock could update its "time" property
once every five minutes, using a timer. Each of the objects with a
timeInterval property would do:
+(NSSet*)keyPathsForValuesAffectingTimeInterval
{
return [NSSet setWithObjects:@"postedTime", @"clock.time", nil];
}
+(NSTimeInterval)timeInterval
{
return [self.clock.time timeIntervalSinceDate:self.postedTime];
}
That way, KVO is responsible for propagating the change implicit in
the tick of the clock. Also, there is one unambiguous keeper of the
time of the last five-minute tick time, so everybody's consistent.
Cheers,
Ken
_______________________________________________
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