Search code examples
iosswiftviewdidload

how to initialize methods in a UIViewController inside of a viewDidLoad method


There is a method for creating data. This method needs to be called only once. So currently this is the structure:

var dataCreated : Bool? = false



override func viewDidLoad() {
    super.viewDidLoad()

    if dataCreated! == false {
        createData()
        self.dataCreated = true
    }
}

Is this the right way to ensure createData() method is called only once? Thank you.


Solution

  • Since you only want createData to be called once per instance of your view controller, then using viewDidLoad is a good place to call it. Further, since viewDidLoad is only called once per instance of the view controller, there is no need for the dataCreated property. You can remove that.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        createData()
    }
    

    Another option would be to call createData from the init method of the view controller. This depends on what createData needs to access. If the createData method needs access to views and outlets, then you must use viewDidLoad.