SwiftUI Life Cycle not supporting CoreData

Viewed 369

I'm creating a new iOS App and wanted to start with SwiftUI instead of Storyboard as backwards compatibility is no problem in this case. Watching WWDC 2020 Videos I noticed the new Life Cycle Option: SwiftUI App. This seemed very interesting as it does not use Storyboards at all anymore, which seems cleaner to me.

Anyway how should I persist my Data since CoreData is not available for this option. I've read that people just manually added CoreData but this also seems odd to me since Apple obviously does not want this currently.

1 Answers

Update

This looks to be fixed now in Xcode 12.0


Original answer

It looks like currently there is no automated way. You need to create your own CoreData container. This can be done in the main app.

The example may look like this:

import CoreData
import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, persistentContainer.viewContext)
        }
    }

    var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "TestApp")
        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)")
            }
        }
    }
}

Note that you have to manually add the data model to your project.

You can take a look at this link for a better explanation:


Alternatively you can create a singleton for your Core Data Stack as proposed here:

Related