Xcode 12 / iOS14 Core Data setup

Hi there,

I'm trying to figure out how to add support for Core Data to an existing project. Looking at the template that Xcode creates it is my understanding that all you need is:

Code Block
NSPersistentContainer(name: "dataModelName")


The extra boilerplate code is mainly for previews or am I on the wrong track there?
Here is how you do it:

Add this code to your AppDelegate file:

Code Block
lazy var persistentContainer: NSPersistentContainer = {
     let container = NSPersistentContainer(name: "Your_App_CoreData_Model_Name")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
       if let error = error as NSError? {
         fatalError("Unresolved error \(error), \(error.userInfo)")
      }
    })
     
     return container
  }()
   
func saveContext() {
let context = persistentContainer.viewContext
     if context.hasChanges {
       do {
         try context.save()
      } catch {
         let nserror = error as NSError
         fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
      }
    }
  }
func managedObjectContext() -> NSManagedObjectContext {
     let managedObjectContext = ModelManager.instance.persistentContainer.viewContext
     
     return managedObjectContext
  }



I appreciate the answer and this would have worked, but since Xcode 12 / iOS 14 there is no more AppDelegate file. SwiftUI works with the @main entry wrapper.
Xcode 12 / iOS14 Core Data setup
 
 
Q