SwiftUI Xcode 12 Core Data FetchRequest issues

I am trying to get Core Data running with the new Multiplatform SwiftUI on Xcode 12.

Since there is no checkbox for Core Data, I looked at some examples on how to build your own Core Data Stack and pass it in.

So fare so good.

However as soon as I try to make a FetchRequest

Code Block swift
struct ContentView: View {
    @FetchRequest(fetchRequest: Entity.fetchRequest()) var entitys: FetchedResults<Entity>
    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}


My app Crashes with:

Fatal error: UnsafeRawBufferPointer with negative count

Here my code:

Code Block swift
import SwiftUI
@main
struct CoreDataTemplateApp: App {
    let context = PersistentCloudKitContainer.persistentContainer.viewContext
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, context)
        }
    }
}


I got the PersistentContainer of the form:

Code Block swift
import CoreData
public class PersistentCloudKitContainer {
    public static var context: NSManagedObjectContext {
        return persistentContainer.viewContext
    }
    private init() {}
    public static var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "Model")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        return container
    }()
    public static 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)")
            }
        }
    }
}


Am I missing something essential here?

My Core Data Model is a single entity with a name property.

Hi Guy, I have the same issue running on Xcode 12 and SwuiftUI with App life cycle over macOS Big Sur.


Code Block
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.'
terminating with uncaught exception of type NSException


Solutioned
In my case the solutions is that the context must be defined inside the struct App.

Code Block
import SwiftUI
@main
struct CoreDataDemoApp: App {
   
private let context = CoreDataStack.context.
var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, context)
        }
    }
}


I had that exact same error but it was because I was trying to add Core Data to an existing project with Xcode 12 beta, so I had copied the Persistence.swift file from a test project I'd make that started out with Core Data.

In my case I was getting that same error:

Fatal error: UnsafeRawBufferPointer with negative count

because I hadn't modified this line in Persistence.swift:
Code Block
container = NSPersistentContainer(name: "HWSCoreDataProject")

Took a while to figure out until I'd commented about everything else :-) but that needs to match the name of your ".xcdatamodeld" file. I thought it was just a name to distinguish containers if you had multiple or something, but apparently not. For example, if your core data model file is "HWSFriendsChallenge.xcdatamodeld" then that line better be:
Code Block
container = NSPersistentContainer(name: "HWSFriendsChallenge")




If you Changed the name of your .xcdatamodel file ensure that the same name you changed it to is used when making your container in AppDelegate.swift as below

let container = NSPersistentCloudKitContainer(name: "Same Name ")
SwiftUI Xcode 12 Core Data FetchRequest issues
 
 
Q