Modifying objects in NSUserDefaults without creating and reinstalling copies

I have a dictionary stored in NSUserDefaults and I need to add / remove elements in this dictionary.

My concern is that for this I need to create a mutable copy of the entire dictionary, change one element and replace the entire dictionary with a new copy.

 copy = [[defaults objectForKey:@"foo"] mutableCopy]; [copy setObject:… forKey:@"bar"]; [defaults setObject:copy forKey:@"foo"]; 

and this is due to even more copying and reinstalling for objects in the hierarchy.

Is there a better way?

I tried to use [defaults setValue:… forKeyPath:@"foo.bar"] , but this does not seem to work (object not changed).

+6
copy cocoa nsuserdefaults nsdictionary
source share
1 answer

I usually create a custom class to store all of my application settings. This class can load modified copies of userDefaults once when the program starts, and then process all incremental saves in the path:

MyPreferences.h

 @interface MyPreferences { NSMutableDictionary allPrefs; } @property (readonly) NSMutableDictionary * allPrefs; - (void)load; - (void)save; @end 

MyPreferences.m

 @implementation MyPreferences @synthesize allPrefs; - (id)init { if ((self = [super init]) == nil) { return nil; } allPrefs = [[NSMutableDictionary alloc] initWithCapacity:0]; return self; } - (void)dealloc { [allPrefs release]; [super dealloc]; } - (void)load { // load all mutable copies here [allPrefs setObject:[[defaults objectForKey:@"foo"] mutableCopy] forKey:@"foo"]; // ... } - (void)save { [defaults setObject:allPrefs forKey:@"app_preferences"]; } @end 

I create an instance of this class in the application deletion, and then call [myPrefs load] when my application starts. Any settings that are changed while the program is running can be changed using myPrefs and then saved by calling [myPrefs save] as desired:

 MyPreferences * myPrefs = [myApplication myPrefs]; [myPrefs setObject:bar forKeyPath:@"allPrefs.foo.bar"]; [myPrefs save]; 

As an added bonus, you can structure the MyPreferences class MyPreferences any way you like, as a result of which the benefits of OO programming will fit into your entire set of preferences. I showed a simple way, just using a mutable dictionary, but you can make every preference in a property and do preprocessing / post-processing for more complex objects like NSColor , for example.

+5
source share

All Articles