Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

NSDictionary to NSUserDefaults

Is there a way to store NSDictionary keys and objects to NSUserDefaults? I mean i know you can...

NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];

[defs setObject:[myDictionary objectForKey:@"myKey"] forKey:@"myKey"]; // continue for every object

But is there some sort of initialization I can do? Basically something that creates the NSUserDefaults from the dictionary. If not I guess ill just have to keep manually adding all the objects every time. Thanks.

1 Answer

Hey Derek,

In iOS everything is possible :). Here is the solution for you:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"Pavel", @"FirstName", @"Palancica", @"LastName", nil];

NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];

[defs registerDefaults:dict]; [defs synchronize];

NSLog(@"First Name = %@", [defs objectForKey:@"FirstName"]); NSLog(@"Last Name = %@", [defs objectForKey:@"LastName"]);

Hope it saved your day.

Regards!!!

Thanks! I literally just found this out a few seconds ago! Good stuff!