At least a couple of times a week somebody posts a question something like this:
My app has 2 view controllers, and I need to get information from the user in one view controller, and pass it to a second view controller. How do I do that?
More generally, the question is, what's the best way to share information between different objects in your app?
I got tired of answering this question repeatedly, and decided to write a sample app that shows how to do it. The idea is to create a single data container object that is a property of the app delegate, and make that data object available to every object in your app that needs it.
Here's what I did:
-I created a generic data container class AppDataObject. This is an ancestor class for a data container object that you would actually use to hold your application's global variables.
-At init time, I added code to the app delegate that create an empty data container object.
-I created a dirt simple protocol, AppDelegateProtocol. This protocol only lists one method, -theAppDataObject. That method lets you ask the app delegate for it's data object.
-I created a subclass of the AppDataObject that actually holds data for a real app. This is where you put the information that you want to share between objects.
Using a protocol means that the only things the objects in your app need to include are the AppDelegateProtocol and the header for your subclass of the app data object. You don't have to #include the header of your app delegate, which makes for good separation between the different objects in your app.
I have posted a complete project, ViewControllerDataSharing, that uses the above method to share information between view controllers. The project uses a navigation controller, and has a root view controller and a second view controller. Each view controller has a UITextView and a slider. The app uses an AppDataObject to pass the value of these fields between view controllers.
I've posted the project to my public iDisk. You should be able to download it simply by clicking the link below: