The app I am developing has 10 controllers. I wanted to share some state information in set up screen to 5 controllers. What is the best strategy from the below options:
- Using NSUserdefaults to store the state information and use it.
- storing the state information in AppDelegate instance and using it in relavent controllers
- Using a singleton instance to maintain the state information and using it at relavent controllers
Which one would be better? Let me know if there are any other options.
The
NSUserDefaultssolution is not a bad one, at least if the values are really going to end up there naturally. Certainly forget about the singleton idea, be it a separate singleton class or the app delegate.There’s also another possibility, one that decreases coupling between the controllers. Instead of relying on one particular class that would expose the settings as properties, have the needed settings as properties on the individual controllers:
Then have one separate class (let’s call it
Factory) that would take care of creating the controllers. The factory would keep note of all the settings and pass the controller the settings it needs. (There’s a sample Xcode project on GitHub showing the Factory approach, but for now it doesn’t contain an example of this particular problem.)The advantage of this solution is loose coupling, you don’t need an extra object (the app delegate,
NSUserDefaultsinstance or someSettingsclass instance) to tweak the behaviour of the controller. The downside is a more verbose controller API. Whether to choose this approach or not depends on the nature of your settings.Of course, it is also possible to come up with a hybrid solution. Create a
Settingsclass that would keep all the settings, exposing them with a nice API (no more-objectForKey:calls), and share a pointer to aSettingsobject to all controllers. You don’t need a singleton for this, see the GitHub sample code linked above. This means tighter coupling, but less verbosity in the interface.