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?
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 ofUIViewController
.In case you don't want to instantiate a new VC using
instantiateViewControllerWithIdentifier
but accessing the instance created by the storyboard from the AppDelegate:@property (nonatomic, strong) myViewControllerClass*vC;
viewDidLoad
inside myViewControllerClass.m I access the shared instance of AppDelegate and feed the property with self:[AppDelegate sharedInstance].vC = self;
I had to use this solution in a complex storyboard and still can't get over the fact that I cannot find an easy way to access all (or at least the ones I need) objects in storyboard simply by addressing their identifiers.
It is not the same thing. In the storyboard you probably have some UI elements laid out. They might have constraints and properties setup through the storyboard. When you instantiate the viewcontroller via the storyboard, you are getting all the instructions for where those subviews are and what their properties are. If you just say
[SomeViewController new]
you are not getting all the instructions that the storyboard has for the view controller.A nice test will be to add a UIViewController to a storyboard and drag a red view onto it. Instantiate it using both methods and see what the differences are.
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
orviewDidLoad
or creating a xib namedSomeViewController.xib
), you'll just get an empty white view and be sad.In Swift you can do the same with,
You will need to give the Identifier in the Storyboard to the SomeViewController and tick the checkmark to Use Storyboard ID