I have a class called “Timestamp”. This class contains a static NSDate variable which is initialized the FIRST time using NSUserDefaults the app opens. This date is turned into a string which is used later. This is how I first configure date:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *string = [defaults objectForKey:@"timestampCheck"];
if (!string) {
Timestamp *tstamp = [[Timestamp alloc] init];
[tstamp setSingleTimeStamp : [NSDate date]];
[tstamp release];
[defaults setObject:@"notFirst" forKey:@"timestampCheck"];
[defaults synchronize];
} else {
Timestamp *ti = [[Timestamp alloc] init];
[ti initializeTimestamp];
[ti release];
}
initializeTimestamp
method is just retrieving the timestamp from the defaults. Which is set in a method called:synchronizeTimestamp
That method is called when the app enters background state.
The Timestamp class looks like this:
- (void)setSingleTimeStamp:(NSDate *)dateProvided {
date = dateProvided;
[date retain];
}
- (void)synchronizeTimestamp {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:date forKey:@"timestampDate"];
[defaults synchronize];
}
- (void)initializeTimestamp {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
date = [defaults objectForKey:@"timestampDate"];
}
- (NSString *)dateStringContainer {
NSDate *tempDate = date;
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:units fromDate:tempDate];
NSInteger year = [components year];
NSInteger month = [components month];
NSInteger day = [components day];
return [NSString stringWithFormat:@"%i - %i - %i", day, month, year];
}
A label’s text in a separate view controller is set to dateStringContainer. Of course when I delete and build my app it shows the right date. But when I quit the app and delete from the multitasking bar the label text is:
1 - 1 - 2001
And date is nil, after some NSLog's
UPDATE:
Ok so basically, the date is working the first time the app opens ( I have to delete the app every single time to do this ), when my app is plugged in. But when I go back to it after removing it from the multitasking bar, the date is incorrect. This means that there is something wrong with my NSUserDefaults code right? Just guessing…
EDIT:
I have noticed that my synchronizeTimestamp method isn’t called. But that may be because I am stopping the app on Xcode, does stopping that app on Xcode turn it into background mode?
You will have to retain the following
wich should be
Since the defaults will return an autoreleased object,
I dont know if this will fix all your problems, but it is certainly a bug