iPhone: How to Pass Data Between Several Viewcontrollers in a Tabbar App

You need a data model object that stores the data for application.

A data model is a customized, standalone object accessible from anywhere in the application. The data model object knows nothing about any views or view controllers. It just stores data and the logical relationships between that data.

When different parts of the app need to write or read data, they write and read to the data model. In your case, view1 would save its data to the data model when it unloads and then view2 would read that data from the data model when it loads (or vice versa.)

In a properly designed app, no two view controllers should have access to the internal data of another controller. (The only reason a view controllers needs to know of the existence of another controller is if it has to trigger the loading of that other controller.)

The quick and dirty way to create a data model is to add attributes to the app delegate and then call the app delegate from the view controllers using:

YourAppDelegateClass *appDelegate = [[UIApplication sharedApplication] delegate];
myLocalProperty = appDelegate.someDataModelProperty;

This will work for small project but as your data grows complex, you should create a dedicated class for your data model.

Edit:

To clarify for your specific case, you would add the call to the data model when the receiver viewController becomes active.

Placing the data in an init method or a viewDidLoad won’t work because in a UITabBar the users can switch back and forth without unloading the view or reinitializing the view controller.

The best place to retrieve changing data is in the viewWillAppear controller method. That way the data will be updated every time the user switches to that tab.

Leave a Comment