I have the following (terible) method that constantly checks the current time, and when a certain time is reached (in this case midnight) an NSLog statement is run once to signify something useful being done:
- (void) checkTime {
while (true){
NSAutoreleasePool *loopPool = [[NSAutoreleasePool alloc] init];
NSDate *now = [[NSDate alloc] init];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"HH:mm"];
NSString *nowDateString = [outputFormatter stringFromDate:now];
if([nowDateString isEqualToString:@"00:00"]){
NSLog(@"Store previous days data..");
BOOL stillMidnight = YES;
while(stillMidnight == YES){
NSDate *latestNow = [[NSDate alloc] init];
NSDateFormatter *latestOutputFormatter = [[NSDateFormatter alloc] init];
[latestOutputFormatter setDateFormat:@"HH:mm"];
NSString *latestString = [latestOutputFormatter stringFromDate:latestNow];
//Check if it is still midnight
if([latestString isEqualToString:@"00:01"]){
//leave while
stillMidnight = NO;
}
}
NSLog(@"No longer midnight");
}
[loopPool drain];
}
}
The above method gets called as follows from the applicationDidFinishLaunchingWithOption method:
[self performSelectorInBackground:@selector(checkTime) withObject:nil];
This code runs the NSLog(@"Store previous days data..") once at midnight, which is what I need, but is there a more elegant solution to this problem?
Thanks,
Jack