views:

670

answers:

1

I'm developing my first iPhone app, and while implementing user preferences, I have a few questions on how to best implement this.

Assume the basic MVC pattern: MainView displaying data stored in a Model object; MainViewController handling the app logic.

For the options, I have an OptionsView and an OptionsViewController. A RootViewController handles swapping of the Main and Options views.

First of all, what about the options data? Would I want to make an NSOjbect-derived class to store them (an OptionsModel)? Or maybe a simple NSDictionary would suffice?

Second, who owns the options data? They are application prefs, but storing them in the AppDelegate seems wrong. MainViewController mostly cares about the options, and OptionsViewController needs to edit them, but those guys don't know about each other, nor should they, probably. RootViewController knows about both, so he's in a good position to pass the options between them, but again, that seems wrong.

Finally, MainViewController will frequently need to access the options. Should he call into the options model each time to get some option, or cache his own copy? I don't like the idea of extra overhead retrieving options data, but having the MainViewController have copies which can get out of sync is also not very appealing.

+3  A: 

Have a look at NSUserDefaults. It is a dictionary style collection class designed for this particular purpose.

You store and retrieve defaults like so:

// Fetch a default
BOOL deleteBackup = [[NSUserDefaults standardUserDefaults] boolForKey:@"DeleteBackup"];

// Save a default
[[NSUserDefaults standardUserDefaults] setObject:@"NO" forKey:@"DeleteBackup"];

NSUserDefaults will automatically take care of reading from and serializing to disk.

Concerning your other question, it depends on the overall architecture of your app. Sending out notifications when the OptionsViewController is finished sounds like a reasonable approach to me. However, you could also just define a method on your MainViewController or app delegate (ie. "-reloadUserDefaults") that you can invoke from your OptionsViewController when it's finished.

briankc
To expand on this further you would also use a Settings bundle which uses (loads) into NSUserDefaults, and also installs your preferences into the Settings application on the iPhone itself. Therefore the user preferences are available to be changed outside of the application itself.This is the preferred method by Apple.
John Bellone
It's not necessarily the preferred method by Apple to have your preferences in both places. See http://tinyurl.com/cqyqja "Providing the same set of preferences in your application might require too many screens and might cause confusion for the user."
Shaggy Frog