When should I use init: and when should I use initWithNibName:bundle: when creating a view controller?
When should I use init: and when should I use initWithNibName:bundle: when creating a
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
-initWithNibName:bundle:is the designated initializer for UIViewController. Something should eventually call it. That said, and despite Apple’s examples (which favor brevity over maintainability in many cases), it should never be called from outside the view controller itself.You will often see code like this:
I say this is incorrect. It puts implementation details (the name of the NIB and the fact that a NIB is even used) into the caller. That breaks encapsulation. The correct way to do this is:
Then, in MYViewController:
This moves the key implementation details back into the object, and prevents callers from accidentally breaking encapsulation. Now if you change the name of the NIB, or move to programmatic construction, you fix it in one place (in the view controller) rather than in every place the view controller is used.