0

Let's say I have custom view controllers which have their own .xib file setted properly.

I also have this extension

class func fromNib<T: UIViewController>() -> T { return T(nibName: String(describing: T.self), bundle: nil) } 

Let's call our custom UIViewController VC.

let customVC = VC() let customVC:VC = .fromNib() 

What is the main difference between the top 2 approaches ? The funny thing is I used both of them, and both work, but not always and not for all of them. Using the first approach I managed to find that whenever you add the controller as a child, it's loadView and lifecycle starts. Using the second approach you have to implement the following 2 things:

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) required init?(coder aDecoder: NSCoder) 

I tried replacing everything that used to have .fromNib with the first approach, in order to skip implementing those methods above, and just doing everything inside viewDidLoad.

Why does the first approach work flawlessly for some controllers, yet for others the outlets are not being connected ?

2
  • Actually, surprisingly, first approach works with .xib files. Somehow xcode knows that your controller is the owner of a .xib file and loads it automagically. Commented Oct 31, 2018 at 15:24
  • Nevermind, I found the bug. I was using the outlets in some controllers within loadView instead of viewDidLoad, and inside loadView outlets are nil. I'm so stupid. Commented Oct 31, 2018 at 15:24

1 Answer 1

1

Nevermind, I found the bug. I was using the outlets in some controllers within loadView instead of viewDidLoad, and inside loadView outlets are nil. I'm so stupid. PS: first approach does work with .xib files. I know there is no connection from code to the .xib file, I guess xcode just knows your ViewController is the owner of a .xib file and loads it automagically.

Sign up to request clarification or add additional context in comments.

1 Comment

you are right, I just did a test. I think the init with nibName constructor default to nil when you are not providing the nibName. And when the nibName is nib, it will try to look for the xib file with same class name to load. Once I renamed the xib file or class name to make them different, this will not work. However if I create a subclass of the view controller using the name of the xib file, and create the subclass it works again, even though in the xib file the view controller class is the super class. Something to learn.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.