I have a UIViewController subclass and I'm trying to figure out what to override such that I can run some initialization code only once per object instance.
The viewDidLoad
method might seem like the obvious answer, but the problem is that viewDidLoad
may run more than once if the controller resets the view due to a memory warning. The initWithNibName:bundle:
, init
, and initWithCoder:
methods also seem like good choices, but which one to override? The awakeFromNib
method is another consideration, but that doesn't seem to be executed in my view controller.
Is there a way to do this that I'm missing?
A UIViewController has 3 methods that involve the initialization of it and its view: init (and init-like methods) loadView. viewDidLoad (delegate method)
Open ImageViewController. swift and add an initializer with name init(coder:image:) . The initializer accepts an NSCoder instance as its first argument and an Image object as its second argument.
They are separate classes: UIView is a class that represents the screen of the device of everything that is visible to the viewer, while UIViewController is a class that controls an instance of UIView, and handles all of the logic and code behind that view.
The UIViewController class defines the shared behavior that's common to all view controllers. You rarely create instances of the UIViewController class directly. Instead, you subclass UIViewController and add the methods and properties needed to manage the view controller's view hierarchy.
UIViewControllers's designated initializer, the method that all other initializers are supposed to call, is -initWithNibName:bundle:
. If you want to initialize something when your view controller is created, override that method.
-viewDidLoad
is meant for any setup that depends on the controller's views. As you point out, that method may run more than once because the views may be loaded more than once. -awakeFromNib
won't help unless your view controller itself exists in a nib, and even then it only makes sense if the thing that you're initializing depends on other objects in that same nib.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With