IOS obtains the sub-Controller on Interface Builder in two ways.
Preparations
On the Storyboard, drag and drop two sub-controllers for a ViewController, and set the identifiers of the two sews to childvc1 and childvc2 respectively.
Effect
Method 1: determine the result based on the identifier
#import ViewController.h#import ChildViewController1.h#import ChildViewController2.h@interface ViewController ()@property (weak,nonatomic)ChildViewController1 * childvc1;@property (weak,nonatomic)ChildViewController2 * childvc2;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.childvc1.view.backgroundColor = [UIColor blueColor]; self.childvc2.view.backgroundColor = [UIColor greenColor]; // Do any additional setup after loading the view, typically from a nib.}-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ if ([segue.identifier isEqualToString:@childvc1]) { self.childvc1 = segue.destinationViewController; } if ([segue.identifier isEqualToString:@childvc2]) { self.childvc2 = segue.destinationViewController; }}@end
Note:
PrepareForSegue is called earlier than viewDidLoad to use weak reference so that it does not participate in the lifecycle of the sub-controller. Method 2: Use the features of KVC to create some common code
#import ViewController.h#import ChildViewController1.h#import ChildViewController2.h@interface ViewController ()@property (weak,nonatomic)ChildViewController1 * childvc1;@property (weak,nonatomic)ChildViewController2 * childvc2;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.childvc1.view.backgroundColor = [UIColor blueColor]; self.childvc2.view.backgroundColor = [UIColor greenColor]; // Do any additional setup after loading the view, typically from a nib.}-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ if ([self respondsToSelector:NSSelectorFromString(segue.identifier)]) { [self setValue:segue.destinationViewController forKey:segue.identifier]; }}@end
Note:
The identifier must be consistent with the declared attributes of the corresponding sub-controller.
Principle-using the dynamic features of KVC
Because the property name of the sub-controller and segue. the identifer is consistent, so you only need to determine respondsToSelector: NSSelectorFromString (segue. identifier) to know whether the current is for the corresponding sub-controller to prepareForSegue the respondsToSelector: NSSelectorFromString (segue. identifier) is whether the corresponding get method is included and assigned by KVC.