Search code examples
iphoneiosviewdidload

Which method(s) in UIViewController is called only once, when the view is first presented? viewDidLoad?


Which method(s) in UIViewController is called only once, when the view is first presented?

The reason I'm asking is I need to call the addObserver method of NSNotificationCenter, and I only need to do it once And, I don't need to call removeObserver when the view goes out of sight. (Actually, I do some light processing when a notification is received when the view is out of sight.)

What is the best practice - what method should I call? Is it viewDidLoad method - can anyone confirm if this method is called only ONCE and never called when the view appears subsequently?


Solution

  • If a view controller allocates its resources programmatically, create a custom initialization method that is specific to your view controller. This method should call the super class’s init method and then perform any class specific initialization.

    In general, do not write complex initialization methods. Instead, implement a simple initialization method and then provide properties for clients of your view controller to configure its behaviors.

    2 steps,

    • The view controller calls its loadView method

    • If the view controller is associated with a storyboard, it loads the views from the storyboard. If the view controller is not associated with a storyboard, an empty UIView object is created and assigned to the view property.

    The view controller calls its viewDidLoad method, which enables your subclass to perform any additional load-time tasks.

    this diagram can give you a better idea

    enter image description here