Wish to know more about the practical differences between init and initWithNibName. SO answers such as this suggests that it is better to call “initWithNibName” indirectly through “init“.
- Are there any circumstances that we need to define “init” and
“initWithNibName” differently ? - Is it possible that any Nib file needs to be loaded more than once
during a single program execution ? - Are questions 1 & 2 inter-related ?
It is not better to call
initWithNibName:indirectly through init. You just want to callinitWithNibName:at some point. You can do that externally or internally. Some people think it’s better to do it internally. I actually have a class called “LayoutUtil” that I keep layout-related helper methods to avoid writing tedious piece of layout-related code over and over. Here is my code to load a UIViewController:And then I can just do:
If you want, you could add a method called ughhhh to a class and call it in there, it doesn’t matter at all. The point is that it is not a better practice to call initWithNibName in the init method though, you just want to make sure you call it at some point when initiating a UIViewController.
A nib file can definitely need to be loaded more than once. Everytime you call initWithNibName on a UIViewController the xib has to be loaded. A lot of people load UIViews that are not owned by a UIViewController like this:
Everytime you call this function you will be loading the nib.
There are certain cases where a nib can be cached. An example would be a UITableView — but the table view implements it’s own cache. The operating system isn’t doing any caching automatically.
initandinitWithNibName:are related in thatinitWithNibName:automatically calls init on an object.