Xcode NSUserDefaultValues-返回的值错误

Xcode NSUserDefaultValues-返回的值错误,xcode,nsuserdefaults,Xcode,Nsuserdefaults,我有一个奇怪的使用NSUserDefaults的例子。我在一个类中设置值,在另一个类中检索它们 当我检索时,应用程序会返回“nil”——这听起来很可疑 有人碰到过这个吗?解决办法是什么 NSUserDefaults *appPreferences = [NSUserDefaults standardUserDefaults]; NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:kFormattedDa

我有一个奇怪的使用NSUserDefaults的例子。我在一个类中设置值,在另一个类中检索它们

当我检索时,应用程序会返回“nil”——这听起来很可疑

有人碰到过这个吗?解决办法是什么

NSUserDefaults *appPreferences = [NSUserDefaults standardUserDefaults];

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:kFormattedDateStr];
NSLog(@"%@", [appPreferences dictionaryRepresentation]);
NSLog(@"startDateString =<%@>", [appPreferences stringForKey:kStartDateKey]);
NSLog(@"targetDateString=<%@>", [appPreferences stringForKey:kTargetDateKey]);
NSDate *targetDate = [df dateFromString:[appPreferences stringForKey:kTargetDateKey]];
[df release], df = nil;
NSUserDefaults*appPreferences=[NSUserDefaults standardUserDefaults];
NSDateFormatter*df=[[NSDateFormatter alloc]init];
[df setDateFormat:kFormattedDateStr];
NSLog(@“%@,[appPreferences dictionaryRepresentation]);
NSLog(@“startDateString=,[appPreferences stringForKey:kStartDateKey]);
NSLog(@“targetDateString=,[appPreferences stringForKey:kTargetDateKey]);
NSDate*targetDate=[df DATEFORMSTRING:[appPreferences stringForKey:kTargetDateKey]];
[df释放],df=nil;
我已再次检查是否正在保存一个文件,并使用相同的键检索值。这可能是因为我将值保存为“objectForKey”并将其检索为“stringForKey”

因此,我转储了NSUserDefaults,它显示了我设置的值。我不明白为什么代码会返回nil

    WebKitWebArchiveDebugModeEnabledPreferenceKey = 0;
    WebKitWebGLEnabled = 0;
    WebKitWebSecurityEnabled = 1;
    WebKitXSSAuditorEnabled = 1;
    WebKitZoomsTextOnly = 1;
    notificationKey = 0;
    selectedGoalKey = "New Goal";
    startDateKey = "2011-06-12 15:00:51 +0000";
    targetDateKey = "2011-06-13 15:00:51 +0000";
}
2011-06-12 07:22:14.634 GoalBuggerPro[10304:207] startDateString =<(null)>
2011-06-12 07:22:20.886 GoalBuggerPro[10304:207] targetDateString=<(null)>
WebKitWebArchiveDebugModeEnabledPreferenceKey=0;
WebKitWebGLEnabled=0;
WebKitWebSecurityEnabled=1;
WebKitxSauditorEnabled=1;
WebKitZoomsTextOnly=1;
notificationKey=0;
选择edgoalkey=“新目标”;
startDateKey=“2011-06-12 15:00:51+0000”;
targetDateKey=“2011-06-13 15:00:51+0000”;
}
2011-06-12 07:22:14.634 GoalBuggerPro[10304:207]startDateString=
2011-06-12 07:22:20.886 GoalBuggerPro[10304:207]targetDateString=

山姆。

问题在于我当时的想法

我将值存储为对象,并将其检索为字符串


将代码更改为使用“objectForKey”后,可以访问正确的值。

请在存储完值后尝试调用
-[NSUserDefaults synchronize]
。抱歉。在哪里设置用户默认值?它们由不同类中的两个单独方法设置<代码>代码NSDate*选中=[[self myDatePicker]date];[appPreferences setObject:selected forKey:kStartDateKey];[appPreferences synchronize]
code
那么kStartDateKey是否实际包含您期望的密钥(“startDateKey”)?与kTargetDateKey相同。是-常量定义为#define kTargetDateKey@“targetDateKey”