我为 NSUserDefaults 设置了一些值,如果我在不退出应用程序的情况下检索它们,一切正常。当我重新启动应用程序时,更改会在 95% 的时间内消失。在 5% 的时间内一切正常。
我第一次面对这个问题。在我的其他应用程序中,我通常不会将 NSString 保存在 NSUserDefaults 中。保存 NSString 的事实可能会导致问题吗?
这是我的代码:
-(void) mayShowFeedbackMessage
{
NSDateFormatter *dateFormatter = [ [NSDateFormatter alloc] init];
[dateFormatter setTimeStyle: NSDateFormatterLongStyle];
[dateFormatter setDateStyle: NSDateFormatterMediumStyle];
if ([ [NSUserDefaults standardUserDefaults] objectForKey: @"ratingsMessage_shown_on_date"])
{
NSString *lastRatingDateString = [ [NSUserDefaults standardUserDefaults]
objectForKey: @"ratingsMessage_shown_on_date"];
NSDate *lastRatingDate = [dateFormatter dateFromString: lastRatingDateString];
DebugLog(@"lastRatingDateString: %@", lastRatingDateString);
DebugLog(@"time since last message: %.0f", [ [NSDate date] timeIntervalSinceDate: lastRatingDate]);
if ( [ [NSDate date] timeIntervalSinceDate: lastRatingDate] >= 120.0f )
{
[self showFeedbackMessage];
NSDateFormatter *dateFormatter = [ [NSDateFormatter alloc] init];
[dateFormatter setTimeStyle: NSDateFormatterLongStyle];
[dateFormatter setDateStyle: NSDateFormatterMediumStyle];
NSString *dateString = [dateFormatter stringFromDate: [NSDate date] ];
[dateFormatter release];
[ [NSUserDefaults standardUserDefaults] setObject: dateString
forKey: @"ratingsMessage_shown_on_date" ];
lastRatingDateString = [ [NSUserDefaults standardUserDefaults]
objectForKey: @"ratingsMessage_shown_on_date"];
DebugLog(@"new date: %@", lastRatingDateString);
}
}
else
{
NSDateFormatter *dateFormatter = [ [NSDateFormatter alloc] init];
[dateFormatter setTimeStyle: NSDateFormatterLongStyle];
[dateFormatter setDateStyle: NSDateFormatterMediumStyle];
NSString *dateString = [dateFormatter stringFromDate: [NSDate date] ];
[dateFormatter release];
[ [NSUserDefaults standardUserDefaults] setObject: dateString
forKey: @"ratingsMessage_shown_on_date" ];
NSString *lastRatingDateString = [ [NSUserDefaults standardUserDefaults]
objectForKey: @"ratingsMessage_shown_on_date"];
DebugLog(@"new date: %@", lastRatingDateString);
}
[dateFormatter release];
}
谢谢。