Question

This is probably an easy question, but I'm a newbie, so I'm drawing a blank.

I have a 2D graphical application whose graphics (implemented in drawRect) depend upon the date. When the date changes, the graphics change, so I figure I need to call

[myView setNeedsDisplay: YES];

when the date changes. I've seen code for timers, but this doesn't seem to be a timer type of scenario. How would I check if the local date has changed, and what class would I put that code in? I assume it would go in the .m file for my main view.

Besides automatically triggering upon a change of date, eventually, the app will need to trigger upon user input (perhaps a button to go forward or backward one day or upon a date picker selection).

The graphics render just fine as is, but I've not coded any date trigger, so while the drawRect code is date specific, it doesn't change when the date changes.

P.S. My basic question, above, has been answered, but now that I go to implement it, I realize I have another issue. I ought to have a property somewhere to track the date whose configuration is currently being displayed. The obvious idea is to add a property to the main view holding an NSDate object. But the way I've coded things, the calculations are done by a method in a subview class. So the question is, how to update the NSDate property of the main view from the subview. An alternative would be to add an NSDate property to the subview, but there are multiple such subviews, and that would seem to be redundant. Any opinion on this?

Was it helpful?

Solution

You can use an NSTimer for this. First, though, you need to figure out when that NSTimer should fire. You can use NSDate, NSCalendar, and NSDateComponents for that:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *todayComponents = [calendar components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSDate *today = [calendar dateFromComponents:todayComponents];
// today is the start of today in the local time zone.  Note that `NSLog`
// will print it in UTC, so it will only print as midnight if your local
// time zone is UTC.

NSDateComponents *oneDay = [[NSDateComponents alloc] init];
oneDay.day = 1;
NSDate *tomorrow = [calendar dateByAddingComponents:oneDay toDate:today options:0];

Once you have tomorrow, you can set a timer to fire on that date:

NSTimer *timer = [[NSTimer alloc] initWithFireDate:tomorrow interval:0 target:self selector:@selector(tomorrowTimerDidFire:) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
// The run loop retains timer, so you don't need to.

And in tomorrowTimerDidFire::

- (void)tomorrowTimerDidFire:(NSTimer *)timer {
    [myView setNeedsDisplay:YES];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top