我为NSUserDefaults设置了一些值,如果我在不退出应用程序的情况下检索它们,一切正常。 当我重新启动应用程序时,更改会在95%的时间内消失。在5%的时间内,一切都被保存好了。
我第一次遇到这个问题。在我的其他应用程序中,我通常不会在NSUserDefaults中保存NSString。可能保存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];
}
感谢。
答案 0 :(得分:13)
在进行必要的更改后添加以下代码解决了这个问题:
[ [NSUserDefaults standardUserDefaults] synchronize];
答案 1 :(得分:1)
对于它的价值,您可以使用属性编辑器查看默认值,看它是否正确写入:
open ~/Library/Preferences/org.your.app.plist
或者只是转储它们:
defaults read org.your.app
答案 2 :(得分:1)
NSuserDefualts没有在游戏崩溃时保存我的值。
使用, [ [NSUserDefaults standardUserDefaults] synchronize];
vales正在保存。