Search code examples
swiftuikitviewdidload

Does defining functions inside viewdidload() save more memory versus defining them outside?


Since viewdidload() is only called once in the lifecycle of that instance of the UIViewController object, does that mean that this example below is a "bad practice" since setBackgroundColor(), a function that is only called once, is unnecesarrily loaded into the memory of the entire class when it really should just exist entirely (defined and called) inside viewdidload()? Or in terms of efficiency, does it not matter where setBackgroundColor() is defined and called?

class MasterViewController: UIViewController {

    func setBackgroundColor() {
        self.view.backgroundColor = UIColor.green
    }

    // Do any additional setup after loading the view, typically from a nib.
    override func viewDidLoad() {
        super.viewDidLoad()

        setBackgroundColor()

    }

    // Dispose of any resources that can be recreated.
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Solution

  • It's not a case of memory usage, it's a matter of loading the view efficiently.

    UIViewControllers control views. But the views isn't created at the same time as the view controller.

    Setting the background colour, indeed, any kind of view configuration, in viewDidLoad is done because when that method is called, the view has been created (although not necessarily displayed) at a convenient point in the view controller's life cycle. If you created the view controller and then called your setBackgroundColor method, the self.view part of the call would cause the view to be created straight away if it hadn't already been created.

    For certain methods, such as view controller presentations, this allows the creation methods to return as quickly as possible without the view being loaded straight away and keeps the UI responsive.

    It's because of this lazy loading of views that UIViewController has the isViewLoaded parameter which returns a Bool for whether the view is loaded into memory or not, but without causing the view to load.