Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIViewController - alloc and init vs. instantiate?

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?

like image 234
franklsf95 Avatar asked Apr 19 '26 14:04

franklsf95


1 Answers

[[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.

like image 170
David Rönnqvist Avatar answered Apr 22 '26 07:04

David Rönnqvist