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
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:
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:
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.