iOS NSDictionary saved to NSUserDefaults not savin

2019-07-04 03:29发布

问题:

I am trying to save a NSDictionary with array values to NSUserDefaults but am having some strange trouble.

My NSDictionary has NSStrings for keys and each value is a NSArray of NSNumbers. When I print the dictionary out, everything is fine. I write this dictionary to NSUserDefaults and if I read it back out right away, everything seams fine. Using this everything seams just fine:

[[NSUserDefaults standardUserDefaults] setObject:self.selectedOptionPositions 
                                          forKey:PREF_OPTIONS_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];

//THIS PRINT EVERYTHING OUT EXACTLY AS IT SHOULD!       
NSLog(@"read after write: %@", [[NSUserDefaults standardUserDefaults] 
                                 objectForKey:PREF_OPTIONS_KEY]);

The problem comes when I create a new instance of the class that handles this. When I make a new instance of the class and in the init method check the NSDictionary like so:

NSLog(@"read initial: %@", [[NSUserDefaults standardUserDefaults] 
                              objectForKey:PREF_OPTIONS_KEY]);

When I print that logging, the NSDictionary contains all of the keys but all of the values are now empty! All newly added keys exist after recreating the class, but no values persist.

What could be wrong here? There are no warnings or errors in the console.

回答1:

Try this:

You can use NSKeyedArchiver to write out your dictionary to an NSData, which you can store among the preferences.

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.selectedOptionPositions];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:PREF_OPTIONS_KEY];

For retrieving data:

NSData *dictionaryData = [defaults objectForKey:PREF_OPTIONS_KEY];
NSDictionary *dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:dictionaryData];

As in the iOS Developer Documentation for NSKeyedArchiver it says that:

NSKeyedArchiver, a concrete subclass of NSCoder, provides a way to encode objects (and scalar values) into an architecture-independent format that can be stored in a file. When you archive a set of objects, the class information and instance variables for each object are written to the archive. NSKeyedArchiver’s companion class, NSKeyedUnarchiver, decodes the data in an archive and creates a set of objects equivalent to the original set.