Loading TestViewController from xib file (Everything works, but I have a question)

I had a TestViewController.swift and a TestViewController.xib presenting the layout of TestViewController.
To load this view controller I had this method:
Code Block
let vc = TestViewController(nibName: "TestViewController", bundle: nil)
self.navigationController?.pushViewController(vc, animated: true)

Everything works well, but if I call empty initializer:
Code Block
let vc = TestViewController()
self.navigationController?.pushViewController(vc, animated: true)

Or with nil nibname
l
Code Block
et vc = TestViewController(nibName: nil, bundle: nil)
self.navigationController?.pushViewController(vc, animated: true)

The application also continues to work without changes. What's the point in explicitly specifying the name of the xib file? What is the difference between three calls in this case?

Replies

In my opinion, it is sort of remains of an ancient iOS habit before storyboard was introduced.

The case passing nil to nibName is described here:

Instance Property nibName

Discussion

...
if you do not specify a nib name, and do not override the loadView() method in your custom subclass, the view controller searches for a nib file using other means. Specifically, it looks for a nib file with an appropriate name (without the .nib extension) and loads that nib file whenever its view is requested. Specifically, it looks (in order) for a nib file with one of the following names:
  1. If the view controller class name ends with the word ‘Controller’, as in MyViewController, it looks for a nib file whose name matches the class name without the word ‘€œController’, as in MyView.nib.

  2. It looks for a nib file whose name matches the name of the view controller class. For example, if the class name is MyViewController, it looks for a MyViewController.nib file.

I cannot find any description of the behavior of the empty initializer init(), but it is expected to work the same as init(nibName: nil, bundle: nil).(As far as I can recall, there was a documentation about this behavior, but it is not found in the current documentations. It may be moved to the archived documents, or it is just me that cannot find it.)

You can test #1 with renaming your xib file to TestView.xib.

The doc also says:

If you use a nib file to store your view controller'€™s view, it is recommended that you specify that nib file explicitly when initializing your view controller

So, you should better avoid your second and third usage.