Skip to content

Saving Preferences

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
  • XML
  • CFPreferences/plist (macoslib)
  • JSON
  • Registry (on Windows)
  • SQLite

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:

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 fine the PreferencesExample useful.

4 Comments

  1. Preferences are not saved closing the application i get always default values set on app.open

    • Paul Lefebvre Paul Lefebvre

      I just tried the example on both Windows and OS X and it is working fine for me. Have you tried stepping through the debugger to see where it is failing for you?

      • in app event handlers CLOSE calling preferences.save raises the following exception: “there’s more than one item with this name and it’s not clear wich it refers”

        thanks

        • Paul Lefebvre Paul Lefebvre

          What version of Xojo are you using? I am not seeing such an error on 2016r2 or 2016r1 on either OS X or Windows.