SwiftUI FetchRequest 错误:“提取请求必须有实体”

glo*_*lob 5 core-data swift swiftui

我正在使用 SwiftUI 和 CoreData 以及 SwiftUI 应用程序生命周期(没有场景或应用程序委托)构建一个小型应用程序。当我运行+构建我的应用程序时,出现以下错误:

'executeFetchRequest:error: A fetch request must have an entity.'
Run Code Online (Sandbox Code Playgroud)

我已检查/验证/重新检查以下内容:

  • 我的[app name].xcdatamodeld文件名与我传递到 NSPersistentContainer 中的文件名相同NSPersistentCloudKitContainer(name: [app name])
  • 实体的名称Car正是我传递到 FetchRequest 中的名称
'executeFetchRequest:error: A fetch request must have an entity.'
Run Code Online (Sandbox Code Playgroud)
  • 我为我的实体 Codegen 选择“手动/无”,生成的类是
@FetchRequest(entity: Car.entity(), sortDescriptors: []) var car: FetchedResults<Car>
Run Code Online (Sandbox Code Playgroud)

带有 .Car 扩展名Identifiable

这是我的整个视图结构,根据我的理解,它应该将环境传递给它的所有“子”视图。

public class Car: NSManagedObject {}
Run Code Online (Sandbox Code Playgroud)

和我的@main结构

struct AppView: View {
    
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Car.entity(), sortDescriptors: []) var car: FetchedResults<Car>
    
    var body: some View {
        List {
            ForEach(car, id:\.self) { item in
                RootView(carData: item)
                    .environment(\.managedObjectContext, self.moc)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我使用调试器单步调试时,一旦返回 WindowGroup,就会出现崩溃。我不确定这是否是有用的信息。

我感谢您的所有帮助,谢谢。

mal*_*hal 1

在检查 Core Data 支持时尝试 SwiftUI 应用程序项目模板中的代码:

MyApp.swift

import SwiftUI

@main
struct MyApp: App {
    let persistenceController = PersistenceController.shared

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, persistenceController.container.viewContext)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

持久.迅速

import CoreData

struct PersistenceController {
    static let shared = PersistenceController()

    static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext
        for _ in 0..<10 {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()
        }
        do {
            try viewContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
        return result
    }()

    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "MyApp")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                Typical reasons for an error here include:
                * The parent directory does not exist, cannot be created, or disallows writing.
                * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                * The device is out of space.
                * The store could not be migrated to the current model version.
                Check the error message to determine what the actual problem was.
                */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)