Posted by Paul Lefebvre
A recent forum conversation asked for tips on how you might create a preference file. Here are some suggestions.
Almost any app you create is going to need to save preferences of some kind. These may be preference that you allow your users to specify or they may be internal settings that you want to retain. Either way, how do you best manage saving preferences?
Your first idea might be to create a bunch of public properties on your App class. Yes, you'll likely want your preferences to be globally accessibly, but cluttering the App class with them is not a good plan. Creating a module or class to encapsulte this information makes more sense. Not only does this give you a place to put all the properties themselves, but you also have a place to put the save and load methods.
There are lots of options when it comes to saving preferences, including:
- simple text files
- binary files
- CFPreferences/plist (macoslib)
- Registry (on Windows)
Personally, I often use XML for saving preferences because it is easy and cross-platform.
I've created a sample project that has a a PreferencesModule that can save and load simple preference information as JSON. I used JSON because it is really simple to save and load, but you could easily extend this example to use just about anything as the file format. Usage is pretty simple. In your App.Open event handler, initialize the preferences module with the file name to use to save the preferences:
Then try to load the preferences:
If Not Preferences.Load Then
// Specify default values
You assign and fetch preference values by using dot notation. So to save a preference for UserID, you would just write:
Preferences.UserID = "TestUser"
You can call Preferences.Save to save the preferences in your App.Close event handler (or whever you want).
I hope you fine the PreferencesExample useful.