Pass data back to the previous controller

11,449

Solution 1

In your second view controller class you create a protocol and delegate. The first view controller will set it self as the delegate in prepareForSegue and implement the protocol methods. The second view controller will then call the methods to pass data back to the first view controller. Here is some code from one of my projects as an example.

@protocol TableSelectorDelegate <NSObject>

@optional
- (void)didMakeSelection:(id)selectionString forType:(NSString *)dataTitle;
- (void)didAddNewValue:(NSString *)newValue forType:(NSString *)dataTitle;

@end

@interface TableSelectorViewController : UITableViewController  

@property (nonatomic, weak) id<TableSelectorDelegate> delegate;

@end

Solution 2

when you set the data you're passing to the second controller you can also set a pointer to the previous one.

Solution 3

The "recommended" way of doing this is using a delegate. Have the first view controller set itself as the delegate of the new view controller during the -prepareForSegue: call, then when you're done, you call whatever delegate methods you've defined.

This is a bit more work than tightly coupling the two controllers, but it actually saves time if you ever find you need to use the controller in a slightly different way. If you watch the WWDC'11 video on using IB and Storyboards, they actually go through this pattern in depth and include code examples and demos, so I recommend taking a look at that.

Share:
11,449
Tom
Author by

Tom

Updated on June 14, 2022

Comments

  • Tom
    Tom about 2 years

    I have two controllers in the storyboard, embedded in a NavigationController, and there is a segue to switch between these.

    Passing data from the first controller to the second one is pretty straightforward by implementing prepareForSegue, and set the properties of the second controller using segue.destinationViewController.

    I should pass back data to the from the second controller to the previous one also. I googled, but I have not found any simple, but working code to demonstrate it.

    Would you be so kind give me a simple sample about the best way to do it?

    Thanks in advance!

  • ari gold
    ari gold over 11 years
  • ari gold
    ari gold over 11 years
    You should also read up on delegates, as described in the accepted answer.
  • huggie
    huggie over 11 years
    For iOS6, there is unwind segue
  • milkypostman
    milkypostman over 11 years
    The second tutorial does not really get around the idea of using a "back" button though.