0
votes

I have a strange case of using NSUserDefaults. I set the values in one class and retrieve them in another.

When I retrieve, 'nil' is returned to the app - and that sounded suspicious.

Has anyone run into this? What is the solution?

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;

I have double-checked that I am saving an retrieving the values w/ the same key. Can it be because I am saving the value as "objectForKey" and retrieving it as "stringForKey" ??

So, I dumped the NSUserDefaults - and it shows the values I set. I am confused as to why the code would return 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)>

Sam.

1
Try calling -[NSUserDefaults synchronize] just after having stored your values.Joost
Sorry. Where do you set the value to user defaults?EmptyStack
They are set by two separate methods in a different class. code NSDate *selected = [[self myDatePicker] date]; [appPreferences setObject:selected forKey:kStartDateKey]; [appPreferences synchronize];code <<<< This is one code fragment. The other is similarSam
And does kStartDateKey actually contain the key you expect ("startDateKey")? Same for kTargetDateKey.Johan Kool
Yes - the constant is defined as #define kTargetDateKey @"targetDateKey"Sam

1 Answers

1
votes

The problem was what I was thinking.....

I was storing the value as an object and retrieving it as string.

After changing the code to use "objectForKey", right value was accessible.