5.3. Passing Data From One Screen to Another

Problem

You want to pass data from one scene to another using storyboards.

Solution

Use segue objects.

Discussion

A segue is an object, just like any other object in Objective-C. To carry out a transition from one scene to another, the storyboard runtime creates a segue object for that transition. A segue is an instance of class UIStoryboardSegue. To start a transition, the current view controller (which will get pushed out of the screen after the segue) receives the prepareForSegue:sender: message, where the prepareForSegue parameter will be an object of type UIStoryboardSegue. If you want to pass any data from the current view controller to the view controller that is about to appear on the screen, you need to do that in the prepareForSegue:sender: method.

Note

For this recipe to make sense, you need to have followed the instructions in Recipe 5.2 and created two view controllers inside a navigation controller on your storyboard.

Let’s implement the prepareForSegue:sender: method in the first view controller:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

  NSLog(@"Source Controller = %@", [segue sourceViewController]);
  NSLog(@"Destination Controller = %@", [segue destinationViewController]);
  NSLog(@"Segue Identifier = %@", [segue identifier]);

}

If you run this app now, you will see the results in the console window. However, you might note that the identifier is nil. Each segue has an identifier that uniquely identifies ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.