0

I am having trouble passing data back between 2 viewControllers. They are linked with a segue and I am trying to link the data generated in the 2nd viewController and use it in the 1st viewController.

The way it works is the user starts at the 1st viewController and navigates to the 2nd viewController which contains multiple settings to choose. When they navigate back to the 1st viewController, I want the data to be passed. With prepareForSegue, it is very simple, but what should I do? Is there a method such as prepareForSegue that works in reverse (i.e going back to the main viewController)? I have tried to use unwindSegues but I am not sure if this is the appropriate method to be using. Can anyone tell me the correct way of setting this up? Or is there a different method I should use? Any help regarding what I should do would be greatly appreciated.

esqew
  • 42,425
  • 27
  • 92
  • 132

2 Answers2

0

The best way to go about this is to use a delegate. See the articles here and here to learn about delegation. This answer and this one may also help.

Community
  • 1
  • 1
KerrM
  • 5,139
  • 3
  • 35
  • 60
0

You don't have to do anything like that. The unwind method looks something like that:

- (IBAction)unwindToPackerView:(UIStoryboardSegue*)sender You have access to segue and you can have reference to your source view controller (2 view controller)

- (IBAction)unwindToPackerView:(UIStoryboardSegue*)sender {

    // you can check is this right segue if you have more than one:
    if ([sender.identifier isEqualToString:@"SegueIdentifier"]) {
         CustomViewController *vc2 = sender.sourceViewController;
         // get the data from source view controller
    }
}

Note that you should add this method to the first view controller.

// Extended

If you want to call unwind segue after button (bar button, etc.) clicked just control drag from the button to the unwind icon (exit icon) in storyboard.

But if you want to run unwind segue programatically (after some action happened, like swipe gesture) you should connect your unwind segue to the view controller (File owner). Simple control drag from view controller (file owner) to the unwind icon in storyboard and choose appropriate segue. In the code when the action (for example swipe) happened call:

- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender
Greg
  • 25,317
  • 6
  • 53
  • 62