How to transfer data from the parent view controller to the child view controller?

How to transfer data from the parent view controller to the child view controller?

I tried to do this with delegates. but i don't think this is an option?

+2
source share
2 answers

Option 1

If you are switching from a parent to a child view controller, simply set the childViewController property from the parent.

customChildViewController.someRandomProperty = @"some random value"; [self presentViewController:customChildViewController animated:YES completion:nil]; 

Option 2

Or you can configure the delegate

Step 1: configure the protocol above the interface in the file ChildViewController.h

 @protocol ChildViewControllerDelegate - (NSDictionary *) giveMeData; @end @interface ..... 

Step 2: creating a delegate property in the interface of ChildViewController.h

 @property (strong, nonatomic) id<ChildViewControllerDelegate>delegate 

Step 3: declare the delegate protocol in ParentViewController.h

 @interface ParentViewController : UIViewController <ChildViewControllerDelegate> 

Step 4: in ParentViewController.m add this method:

 - (NSDictionary *) giveMeData { NSMutableDictionary * dataToReturn = [[NSMutableDictionary alloc]init]; dataToReturn[@"some"] = @"random"; dataToReturn[@"data"] = @"here"; return dataToReturn; } 

Step 5: declare a delegation property before starting childViewController.

 childViewController.delegate = self; [self presentViewController:childViewController animated:YES completion:nil]; 

Step 6: in the child view controller, whenever you need data, add this

 NSMutableDictionary * dataFromParent = [self.delegate giveMeData]; 

parentVC will run 'giveMeData' and return an NSMutableDictionary (set up for any data you want)

+12
source

You can access your child controllers:

 NSArray *children = self.childViewControllers; 
+1
source

All Articles