1

I have 2 views, ParentViewController and ChildViewController; I want to nest ChildViewController inside ParentViewController. I have designed ParentViewController and ChildViewController in Storyboard. ParentViewController.m contains the logic for the parent and ChildViewController.m contains the logic for the child. In ParentViewController.m I add the child like so:

 ChildViewController *childVC = [self.storyboard instantiateViewControllerWithIdentifier:@"ChildSBI"];
 [self addChildViewController:childVC];

My Question: How can I receive information (like an NSString) from the child back to the parent? Should I do this through delegation?

Apollo
  • 8,874
  • 32
  • 104
  • 192

1 Answers1

1

A common pattern would be to have the child as a property of the parent, and have the parent be a delegate of the child. The first thing you need to do is make your own protocol.

// MyProtocol.h
- (void)heyParentSomethingHappened:(Something)something;

Next, make the child a property of the parent so they can talk through delegation.

// ParentVC.m
@interface ParentVC()
@property (nonatomic) ChildVC *child
@end

Now that the parent has the child as a property, they need some way to talk. This is where the delegation comes in. Have the parent conform to MyProtocol.

// ParentVC.h
@interface ParentVC : UIViewController <MyProtocol>

Now that the parent conforms to your special protocol, have the child make it a delegate.

//ChildVC.h 
@interface ChildVC : UIViewController
@property (nonatomic) id <MyProtocol> delegate.
@end

Now that the child has the delegate property, set it to the parent and you are good to go.

// ParentVC.m
- (id)init {
    // do your init
    self.child.delegate = self // both (child.delegate, self) conform to <MyProtocol>, so no type mismatch.
}

Now when your child needs to alert your parent of something, they have a formal way of talking through the protocol + delegation.

// ChildVC.m
- (void)someFunc {
    [self.delegate heyParentSomethingHappend:[Something new]];
}

Remember to always include the protocol file when using it.

Brian Tracy
  • 6,801
  • 2
  • 33
  • 48