views:

33

answers:

2

My question is about the best way to implement passing of information between UIViewControllers.

If I have an application with 2 ViewControllers and for example a user selects an item in ViewControllerA which should then show the item and more details in ViewControllerB.

What would be the best way to implement this? via the appdelegate? or by passing a reference to ViewControllerA into ViewControllerB? Appreciate any help or examples of the best way to do this.

+1  A: 

ViewControllerA (VCA) would maintain a reference to ViewControllerB (VCB). VCB would maintain a reference to the selected object as an ivar. When the user chooses an object in VCA, VCA instantiates VCB (if not already instantiated), sets VCB's selectedObject property to that object, and then pushes VCB. VCB reads from the object assigned to its selectedObject property to draw its information into the view.

In VCA, for every one of the "items" that the user can select, there needs to be an underlying object instance backing that item. For example, a UITableView might be backed by an NSArray of Vegetable objects if the user is selecting from a list of vegetables.

In general, try to keep data sharing between controllers to a minimum. Have them refer to model objects instead to get their data.

alexantd
thanks alexantd, will try this out and see how it feels.
kevj
A: 

Try using the MVC design pattern. Put all shared state information into a Model object (M of MVC) created at a higher or the top level of your app. When creating your two view controllers, give them access to the model object (by setting a property in each view controller). Then the view controllers can store and access any shared state required, and you will have it nicely centralized for debugging, storing, extensibility, reuse, etc.

hotpaw2
thanks hotpaw2, this makes sense, will try it out.
kevj