how to save NSDictionary in NSUserDefaults

hello

i am able to save simple user preferences
like strings, values or bools

but now that i am trying to save more complex user data stored in NSDisctionary
i get error saying i am trying to store non property values:

[[NSUserDefaults standardUserDefaults] setObject:myDictionary forKey:@"savedData"];

i confirmed in the docs that it is possible to save NSArray and NADictionary
i though my issue was because i am trying to save a dictionary of custom classes

but i tried with a simple dictionary with just NSStrings there and it ithrew the same error

i also tried to use the NSArchiver technique described to save NSColor but i also got the same error

pls help !
my users are not able to retrieve saved prefs...

MBP c2d 2.16 / iMac g5 2.1, Mac OS X (10.5.4)

Posted on Sep 7, 2008 9:47 AM

Reply
2 replies

Sep 7, 2008 10:22 AM in response to Nonnus

Hello Nonnus,

Your custom classes in the NSDictionary wouldn't work because the documents of NSUserDefaults says so. However, just a NSDictionary with only NSStrings should work. In fact, I tried the following and it worked without a problem.

NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSDictionary* my_dict = [NSDictionary dictionaryWithObject: @"value" forKey: @"key"];
[defaults setObject: my_dict forKey: @"myDict"];
NSLog (@"myDict has been set");


Jake

Sep 7, 2008 10:43 AM in response to Nonnus

tx qlot for your help and attention 🙂

i knew it was stated as possible on the docs
but first attempt threw same errors

i just did some further testing on blank project
(nothing like ablank canvas for testing;)
and i am actually able to save a nsdictionary with strings so i can find a workaround for now 🙂

i still cannot archive other classes like uicolor to get into nsdefaults as well

i am trying to follow their docs but the NSArchiver keeps giving errors:

UIColor* myColor = [UIColor blueColor];
NSData *myData = [NSArchiver archivedDataWithRootObject:myColor];

error: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ' * -encodeInt:forKey: only defined for abstract class. Define -[NSArchiver encodeInt:forKey:]!'

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

how to save NSDictionary in NSUserDefaults

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.