MyLocations - CoreData

Hi Matthijs,

I’m going through the CoreData chapter of MyLocations. The AppDelegate file contains two variables declared with the word “lazy”.

lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: “DataModel”)
container.loadPersistentStores(completionHandler: {
storeDescription, error in
if let error = error {
fatalError(“Could load data store: (error)”)
}
})
return container
}()

and

lazy var managedObjectContext: NSManagedObjectContext = self.persistentContainer.viewContext

My question is related with the first block of code used to load the data model and to connect it to a SQLite data source: if the closure { let container… return container }() parentheses are designed to invoke it immediately why do we need to declare it as “lazy” (which is meant to delay its execution to a later date). Aren’t they contradicting each other?

Thanks

I suppose it depends on what you meant by ‘immediately’. Lazy variables aren’t created when the instance is initialised, they’re created when they’re called for the first time. The closure isn’t called until the first time the persistent container is requested in code, which might happen the first time the managed object context is requested in code, rather than during initialisation. Until either is requested, neither exists.