Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to initialize something ONCE in a UIViewController

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?

like image 703
chris Avatar asked Jun 13 '11 18:06

chris


People also ask

Which of the following method is called after UIViewController is initialized?

A UIViewController has 3 methods that involve the initialization of it and its view: init (and init-like methods) loadView. viewDidLoad (delegate method)

How do I initialize a view controller in Swift?

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.

What is the difference between UIView and UIViewController?

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.

What is a UIViewController subclass?

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.


1 Answers

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.

like image 135
Caleb Avatar answered Oct 20 '22 01:10

Caleb