Original blog, reproduced please indicate the source
Blog.csdn.net/hello_hwc
Preparatory work
Drag and drop two sub-controllers for a viewcontroller on the storyboard, and set the identifier of the two segue to CHILDVC1,CHILDVC2 respectively
Effect
Method one, according to Segue's identifier to judge to obtain
#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 {[SuperViewdidload]; Self. CHILDVC1. View. BackgroundColor= [UicolorBluecolor]; Self. CHILDVC2. View. BackgroundColor= [UicolorGreencolor];additional setup after loading the view, typically from a nib.}-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (ID) sender{if([Segue. Identifierisequaltostring:@"CHILDVC1"]) { Self. CHILDVC1= Segue. Destinationviewcontroller; }if([Segue. Identifierisequaltostring:@"CHILDVC2"]) { Self. CHILDVC2= Segue. Destinationviewcontroller; }}@end
Two points to note
- Prepareforsegue here to be called earlier than viewdidload
- Use the weak reference to not participate in the life cycle of the child controller
Mode Two, create some common code with KVC's features
#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 {[SuperViewdidload]; Self. CHILDVC1. View. BackgroundColor= [UicolorBluecolor]; Self. CHILDVC2. View. BackgroundColor= [UicolorGreencolor];additional setup after loading the view, typically from a nib.}-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (ID) sender{if([ SelfRespondstoselector:nsselectorfromstring (Segue. Identifier)]) { [ SelfSetvalue:segue. DestinationviewcontrollerForkey:segue. Identifier]; }}@end
Note that here's the
The identifier of segue must be consistent with the properties of the corresponding sub-controller being declared.
Principle-using the dynamic characteristics of KVC
- Because the child controller's property name is consistent with Segue.identifer, only the respondstoselector:nsselectorfromstring (Segue.identifier) needs to be judged You know that the current is not for the corresponding sub-controller to Prepareforsegue
- The respondstoselector:nsselectorfromstring here (segue.identifier) is whether it contains a corresponding Get method
- Assignment by means of KVC
Two ways IOS Gets a sub-controller on Interface Builder