2

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.

pawello2222
  • 46,897
  • 22
  • 145
  • 209
Deitsch
  • 1,610
  • 14
  • 28
  • 2
    I haven't used this but my guess is since you no longer get an AppDelegate class the CoreData set up can't be placed there and there is currently no support for doing this automatically. You can still use Core Data of course but you need to create your own manager class (as many already do) and you have to add the model file manually but once that is done you can use Core Data as normal. – Joakim Danielson Jul 29 '20 at 15:14
  • That's a good guess. Makes a lot of sense that the removal of AppDelegate is the only reason for this. – Deitsch Jul 29 '20 at 15:22

1 Answers1

1

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:

pawello2222
  • 46,897
  • 22
  • 145
  • 209