What is the difference between the following two ways of instantiating view controllers?
MyViewController *vc = [[MyViewController alloc] init];
// present vc...
vs.
[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"MyViewControllerScene"]
It seems that alloc init can magically identify the proper scene in the storyboard; how does this happen? Is it invoking instantiateViewControllerWithIdentifier: under the hood? Which is the preferred way of instantiating a view controller? Will the first way result in memory leak or extraneous view controller instances?
[[MyObject alloc] init] creates a new object. It's not retrieving an object from a Storyboard, just allocating memory for it and instantiating it.
instantiateViewControllerWithIdentifier: creates a new view controller (if the identifier exists in the storyboard) and configures it according to how the view controller was configured object in the Storyboard file.
Both cases will create a new instance for each call.
If you have configured a view controller in the Storyboard (for example connected outlets, actions, etc.) and you want to retrieve it, you should read it from the Storyboard. If you would create a new instance (not from the Storyboard) it would not have this configuration.
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