Using Core Data with SwiftUI App Protocol

Is it possible to use CoreData with the newly announces SwiftUI App Protocol for 100% SwiftUI apps. If I need to create an app with persistant storage, is there a way to achieve this with the new protocol? I like the idea of having my app fully compatable across all systems.

Thanks.

Accepted Reply

Yes, you can setup everything you need directly in your App as following:

Code Block swift
@main
struct SampleApp: App {
    @Environment(\.scenePhase) private var scenePhase
    var body: some Scene {
        WindowGroup {
            MovieList()
                .environment(\.managedObjectContext, persistentContainer.viewContext)
        }
        .onChange(of: scenePhase) { phase in
            switch phase {
            case .active:
                print("active")
            case .inactive:
                print("inactive")
            case .background:
                print("background")
                saveContext()
            }
        }
    }
    var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "SampleApp")
        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)")
            }
        }
    }
}

Replies

In Beta 6 there is an option to use Core Data but the template it creates has an error.
Cannot find 'Item' in scope
I find this an odd bug because the data model contains an entity called Item.
Is there any way to resolve this?
@Davidxo I was able to resolve the Cannot find 'Item' in scope error by doing the following:
  1. Quit Xcode

  2. Reopen Xcode

  3. Shift + ⌘ + K (clean)

  4. ⌘ + B to rebuild

@spellcasterdragonborn

Hah, Apple uses the underscore to format italic text, so when I type your name in here the underscores cause formatting chaos.

Yes, at this current moment in time, I agree with you - there is no need to use @StateObject.

So to be clear, at this current moment in time, I understand that ALL WE NEED to access Core Data features throughout our SwiftUI App is an NSManagedObjectContext.

To answer your question the long way round...

Apple does not let us edit our answers so when I wrote my original answer, this was all fairly new to me. If I could change the answer - as I have in my SwiftUI universal apps that use Core Data - I would change the following...

Code Block
    lazy var persistentContainer: NSPersistentContainer = {...}

Change to:

Code Block
private lazy var persistentContainer: NSPersistentContainer = {...}

My reason is that there are only three properties that I believe should be publicly available in my class implementation of PersistentStore...
  1. static let shared, ...and through this one line singleton...

  2. var context, to use throughout the app; and

  3. func save, for convenience.

If you check Apple's response to my forum question with the abstract title New toolbar appearance in macOS 11, you can see their advice "and then your SwiftUI App could hold on to an instance of that (ed. custom) class in a variable." In their response, they also suggest I should watch the SwiftUI Data Essentials WWDC session for inspiration. From my multiple viewings of this session, at the time I deducted that the hint was to use an @StateObject for my PersistentStore class, which is why I included it in my Core Data SwiftUI Xcode projects and in my original answer. It also made it easy for me to call save from the .onChange(of: scenePhase) view modifier.

In hindsight and following review of the template that Apple includes in more recent Xcode 12 betas, I was complicating their hint. (As per Apple's beta Core Data template) the instance of that persistent container custom class could be as simple as...
Code Block
    let persistenceController = PersistenceController.shared

or, per my previous answer...
Code Block
    let persistentStore = PersistentStore.shared

However, at this current moment in time, I would remove the @StateObject instance of my PersistentStore class. Not that I have done that yet in my SwiftUI projects (no reason, just not got around to it). It seems important for me to add subtext here - I am still developing an understanding of how @StateObject property wrapper operates in the App lifecycle, so in the future and with a better understanding, I might change this decision.

(PS: I just commented out @StateObject private var persistentStore = PersistentStore.shared in one project as a test and my iOS and macOS targets appear to build and run without issue. There seems to be a minor drop in memory usage, but this is speculative without taking steps to measure it properly.)


Yes, you can setup everything you need directly in your App