Best practices for handling user preferences in an iPhone MVC app?

旧时模样 提交于 2019-12-18 04:24:15

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/962591/best-practices-for-handling-user-preferences-in-an-iphone-mvc-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!