Jules
Jules

Reputation: 7766

How to save / Load NSUserDefaults for backup purposes?

Is this code correct to load and save NSUserDefaults.

// Load
    NSDictionary *dict = [[NSUserDefaults standardUserDefaults] 
         dictionaryRepresentation];

// Save
    NSDictionary *dict =  ....
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults registerDefaults:dict];
    [defaults synchronize]; << Not sure if this is needed

I'm using JSON to hold the dictionary contents and I'm having problems. I'd just like to know if this code is correct, before I look elsewhere for my problem.

Upvotes: 0

Views: 1089

Answers (2)

Cyprian
Cyprian

Reputation: 9453

// Get

NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:@"myDictionary"];

// Set

NSDictionary *dict = ...

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

Upvotes: 0

CRD
CRD

Reputation: 53000

Your Load code will get you a dictionary of all the current default values.

[Note This will probably be much larger than you expect as Mac OS installs a raft of defaults, you might want to make it smaller. For example, you can limit the dictionary to just those defaults in your domain which differ from their registered default using:

NSDictionary *userDefaults = [[NSUserDefaults standardUserDefaults] persistentDomainForName:@"<your bundle identifier>"];

end note]

Your Save code probably doesn't do what you expect, it installs the values you are restoring as the defaults for those keys - so if you support "Restore to Default Settings", or something similar, then these are the values that would result. What you probably want to do it set the current value of the keys, this can be done with a simple loop:

NSDictionary *dict =  ....
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
foreach(id key in dict)
   [defaults setObject:[dict objectForKey:key] forKey:key];

The above code is only an outline, you may need to take care what preferences you save/restore and in what order - but all that depends on your application.

Upvotes: 2

Related Questions