What is the functional difference between instantiating a View Controller from the storyboard and creating a new instance of it? For example:
#import "SomeViewController.h" ... SomeViewController *someViewController = [SomeViewController new];
versus
#import "SomeViewController.h" ... UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil]; SomeViewController *someViewController = [storyboard instantiateViewControllerWithIdentifier:@"SomeViewController"];
In either case, is someViewController
effectively the same thing?
In the Storyboard, select the view controller that you want to instantiate in code. Make sure the yellow circle is highlighted, and click on the Identity Inspector. Set the custom class as well as the field called "Storyboard ID". You can use the class name as the Storyboard ID.
Apple introduced them in iOS 9 and macOS 10.11. They do exactly what I needed. They allow you to break a storyboard up into multiple, smaller storyboards. A storyboard reference ties multiple storyboards together, creating one, large, composite storyboard.
instantiateViewController(withIdentifier:)Creates the view controller with the specified identifier and initializes it with the data from the storyboard.
The main difference is in how the subviews of your UIViewController
get instantiated.
In the second case, all the views you create in your storyboard will be automatically instantiated for you, and all the outlets and actions will be set up as you specified in the storyboard.
In the first, case, none of that happens; you just get the raw object. You'll need to allocate and instantiate all your subviews, lay them out using constraints or otherwise, and hook up all the outlets and actions yourself. Apple recommends doing this by overriding the loadView
method of UIViewController
.
In the second case, the view controller will load its view from the storyboard and you will be happy.
In the first case, it won't. Unless you've taken other steps (like overriding loadView
or viewDidLoad
or creating a xib named SomeViewController.xib
), you'll just get an empty white view and be sad.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With