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.
e.james
source share