Reputation: 1341
I'm working on a project in which I'm using xib instead of the storyboard so I want to instantiate my UIViewControllers from xibs, and I saw two methods of doing it with the first one being
let viewController = UINib(nibName: "ViewController", bundle: NSBundle.mainBundle()).instantiateWithOwner(nil, options: [:]).first as! ViewController
And there's also this method
let viewController = ViewController(nibName: "View", bundle: NSBundle.mainBundle())
Which I always see floating around. Why should I use the second method and not the first, and is there a downside to using the first method, and is it considered bad practice? To clarify the first method is instantiating the whole ViewController from the xib. As in the xib has a UIViewController directly put in there, and the second one has the view that has the view controller as the owner.
Upvotes: 2
Views: 3212
Reputation: 4424
That's an opinion based question (or rather asking for an opinion as answer), but I'll let it slide. :)
The reason why I'd say the first method is "bad practice" or obscure, as Phillip Mills correctly said) is that you're basically making assumptions on the xib and potentially load more than you must. The second method is suited for a xib that's specifically belonging to your ViewController class (if the name fits, you don't even have to specify that, at least in the Objective-C equivalent). Hence the xib is a parameter of the initializer.
The first method takes a longer route. It loads a nib (and that might include any other objects in that, too). Then you assume that the first object on its top level is the view controller you want. One accidental drag in your storyboard and you'll be having fun raising your eyebrows for unexpected behavior. Also you ommit the owner parameter, which might or might not have consequences depending on what you do.
In general the first method is using a method that's more meant to be used for xibs that are containers for multiple objects (not necessarily view controllers), while the second one is the usual way to go (or "best practice") when loading a view controller with its associated xib file.
You can go the first route, but that's basically hiking on socks, imo. It works, but people will look at you in a weird way...
Upvotes: 2