My app has a main screen that the user always starts at, and from which I want to display other views programmatically. I set up the app identically to the approach in “Beginning iPhone Development” Ch. 6, which is to use a RootViewController that loads in other view controllers.
The book uses a button to trigger loading the next view controller, but in my app I need to swap controllers at the end of function calls and to share data (processed UIImages, etc) between views. I am not using a tab bar or navigation controller.
What I’m wondering is, should I just make my MainViewController the root controller and presentModalViewControllers from there? I’d like to keep the root model but I don’t quite understand how to hook it all up and share data. I’ve seen posts that mention using protocols and notifications but I haven’t wrapped my head around it yet. Any advice is appreciated.
What you want to do is add a Cocoa property in your main view controller that references the object instances which you want to share with subordinate view controllers.
For example, if we want to share an
NSArray, we specify its property in the main view controller header:In the implementation, add the
@synthesizedirective and remember toreleasethe array in-dealloc:You also want to add this property to view controllers that are subordinate to the main view controller, in the exact same way. In their headers, specify the same variable name and property description.
In your main view controller, when you are ready to push a subordinate view controller, you set the subordinate view controller’s property accordingly just before pushing:
Likewise in your subordinate view controller, it will need to set its subordinate’s array property accordingly, just before it pushes its own sub-sub-view controller.
By setting references in this way, each view controller is pointed at the same array, containing the desired elements.
To use the array, just call
self.myArray, e.g.[self.myArray objectAtIndex:index]to get an object at a given index.