Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate View Controller from Storyboard vs. Creating New Instance

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?

like image 594
Benjamin Martin Avatar asked Sep 30 '14 23:09

Benjamin Martin


People also ask

How do I instantiate a view controller from storyboard?

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.

Can we use multiple storyboards in one application?

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.

What is instantiateViewController in Swift?

instantiateViewController(withIdentifier:)Creates the view controller with the specified identifier and initializes it with the data from the storyboard.


2 Answers

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.

like image 131
dpassage Avatar answered Sep 24 '22 18:09

dpassage


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.

like image 37
rob mayoff Avatar answered Sep 21 '22 18:09

rob mayoff