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 preferences 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
- XML
- CFPreferences/plist (macoslib)
- JSON
- Registry (on Windows)
- SQLite
Personally, I often use JSONĀ for saving preferences because it is easy and cross-platform.
I’ve created a sample project that has 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:
PreferencesModule.Initialize("PreferencesExample")
Then try to load the preferences:
If Not Preferences.Load Then // Specify default values End If
You assign and fetch preference values by using dot notation. So to save a preference for UserID, you would just write:
Preferences.UserID = "TestUser"
The code users operator_lookup (which I did a webinar about last summer) to dynamically look up the preference name (“TestUser”) in a JSONItem at run time.
You can call Preferences.Save to save the preferences in your App.Close event handler (or whever you want).
I hope you find the PreferencesExample useful.