UserDefaults (Java & otherwise): registering a baseline
UserDefaults (Java & otherwise): registering a baseline
- Subject: UserDefaults (Java & otherwise): registering a baseline
- From: Bill Bumgarner <email@hidden>
- Date: Fri, 28 Dec 2001 01:28:06 -0500
If you want to register a set of defaults to provide baseline behavior
within your application -- a very good idea -- I would recommend placing
the defaults into a property list within the main bundle and
loading/registering the defaults as the application launches.
This makes it extremely easy to add new defaults as well as providing a
single place to view the baseline defaults within both development and
production contexts. Once the app has shipped, the knowledgeable cocoa
user can always delve into the app wrapper to see the definitive set of
baseline defaults.
To do this, create a property list file as a resource within your
project-- maybe 'Defaults.plist'. Contents something like (these happen
to be ripped from TextEdit and are completely bogus):
{
AppleSavePanelExpanded = YES;
CheckSpellingAsYouType = 1;
DeleteBackup = 0;
NSColorPanelMode = 6;
NSDefaultOpenDirectory = "/Volumes/PBX No Slide";
NSFontPanelLastUsedPane = 0;
}
Then, do something like the following in the app delegate:
- (void) applicationDidFinishLaunching: (NSNotification *) aNotification
{
NSString *registrationDefaultsPath = [[NSBundle mainBundle]
pathForResource: @"Defaults" ofType: @"plist"];
NSString *registrationDefaultsString = [NSString
stringWithContentsOfFile: registrationDefaultsPath];
NSDictionary *registrationDefaults = [registrationDefaultsString
propertyList];
[[NSUserDefaults standardUserDefaults] registerDefaults:
registrationDefaults];
}
Some error checking would be prudent. Converting the above to Java
should be fairly straightforward; see the NSPropertyListSerialization
class.
Defaults registered via -registerDefaults will always be overridden by
defaults provided on the command line or in the user's defaults
environment.
If you need to slap a hunk of NSData into the defaults database --
something that should generally be avoided in that the defaults system
really isn't designed to handle big hunks of binary state (Application
Support is more appropriate)-- it is trivial to write the code necessary
to spew the property list encoded NSData out to stdout such that it can be
copy/pasted into the target property list.
And, of course, the property list could be expressed as XML for that added
bit of TLA compliance....
b.bum