0

I've seen many ways of passing data from a view controller back to its parent in the navigation stack and even though I think the case that I'm going to describe should be quite common, none of these seem to solve it. What I want to do:

  1. Push a child view controller onto the navigation stack. I set up its properties in the parent view controller's prepareForSegue(_:sender).
  2. Edit the properties of the child view controller. Until here everything works.
  3. When tapping the arrow back button (in the top left corner), the child view controller should he popped (which happens automatically) and needs to pass the edited data back to the parent.

This would be easy if I could set up an unwind action in the storyboard, but this is not possible since the arrow back button is displayed only at runtime. prepareForSegue(_:sender) doesn't seem to be called on the child when pressing that arrow. Neither are canPerformUnwindSegueAction(_:fromViewController:withSender) or unwindForSegue(_:towardsViewController) or segueForUnwindingToViewController(_:fromViewController:identifier:) on either the child or the parent.

As suggested here I could override the child's viewWillDisappear method and access the parent from the navigation stack, but there must be a way for the parent to access the child somewhere, or this would be bad design, right? I'm grateful for any help! I'm targeting iOS 7+.

Community
  • 1
  • 1
Nickkk
  • 2,261
  • 1
  • 25
  • 34
  • It's partially personal preference, but MVC-esque design avoids this problem all together. If your model changes in the 2nd VC, you can simply update it from the same source when you pop back to your 1st VC – GetSwifty Jun 20 '16 at 23:56
  • http://stackoverflow.com/questions/19343519/pass-data-back-to-previous-viewcontroller this might help – Avinash12388 Jun 21 '16 at 00:08
  • @PEEJWEEJ But this is exactly the problem, how to access the parent when popping the child? – Nickkk Jun 21 '16 at 10:14
  • I'm saying don't. Store/access the data with other classes and reload the data on a back. – GetSwifty Jun 21 '16 at 13:57
  • @PEEJWEEJ The other problem described is how to detect the "back" in the parent so that it can reload the data. – Nickkk Jun 21 '16 at 15:59
  • viewWillAppear is called during this process. You can reload the data at that time. – GetSwifty Jun 21 '16 at 19:08
  • @PEEJWEEJ The problem then would be how to detect in `viewWillAppear` that this particular child view is being popped. Please consider adding an answer to sum up your observations :-) – Nickkk Jun 21 '16 at 19:24

1 Answers1

0

You can use delegate and setup like:

  • child is as property of parent controller.
  • parent is as delegate property of child controller. (delegate alway weak attribute)

You can access to parent any where from child just use child.delegate. And child from parent via property.

larva
  • 4,687
  • 1
  • 24
  • 44