Search code examples
iosswiftmkmapview

Is there a difference between creating a view object explicitly in the scope of the class vs the loadView function?


I was following a tutorial from a book and want to move ahead without reading the code in the book to see what I would come up with on my own based on the instructions. My code is a little different by creating the MKMapView object globally outside of the loadView() function however the book creates the MKMapView object inside the loadView() function. Both processes work so I want to know if there is much of a difference or preference among the iOS development community?

Thank you in advance.

My code:

import Foundation
import UIKit
import MapKit

class MapViewController: UIViewController {

    var mapView: MKMapView = MKMapView()

    override func loadView() {
        view = mapView
    }

}

The book's code:

import Foundation
import UIKit
import MapKit

class MapViewController: UIViewController {

    var mapView: MKMapView!

    override func loadView() {
        mapView = MKMapView()
        view = mapView
    }

}

Solution

  • The difference is in the first case the map view is created right when the view controller is initialized.

    In the second case, the view is lazily created when the viewController.view is first accessed.

    I'd recommend the second approach since that's in line with Apple's recommendation.