Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I usually create a custom class to hold all of my application preferences. That class can load mutable copies of the userDefaults once, when the program starts, and then handle all of the incremental saves along the way:</p> <p><strong>MyPreferences.h</strong></p> <pre><code>@interface MyPreferences { NSMutableDictionary allPrefs; } @property (readonly) NSMutableDictionary * allPrefs; - (void)load; - (void)save; @end </code></pre> <p><strong>MyPreferences.m</strong></p> <pre><code>@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 </code></pre> <p>I create an instance of this class in my application delegate and then call <code>[myPrefs load]</code> when my application launches. Any preferences changed while the program is running can be modified through <code>myPrefs</code>, and then saved by calling <code>[myPrefs save]</code> as desired:</p> <pre><code>MyPreferences * myPrefs = [myApplication myPrefs]; [myPrefs setObject:bar forKeyPath:@"allPrefs.foo.bar"]; [myPrefs save]; </code></pre> <p>As an added bonus, you can structure the <code>MyPreferences</code> class any way you like, bringing the benefits of OO programming to the whole set of preferences. I showed the easy way here, simply using a mutable dictionary, but you can make each preference into a property, and do pre/post processing for more complicated objects like <code>NSColor</code>, for instance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload