获取请求必须有一个在 SwiftUI 中使用@FetchRequest 的实体
Fetch request must have an entity using @FetchRequest in SwiftUI
我正在尝试使用@FetchRequest 通过CoreData 从SQLite 数据库中获取所有记录。我已经设置了 CoreData 堆栈,如下所示:
class CoreDataManager {
private let persistentContainer: NSPersistentContainer
static let shared = CoreDataManager()
var context: NSManagedObjectContext {
return persistentContainer.viewContext
}
private init() {
persistentContainer = NSPersistentContainer(name: "FooModel")
persistentContainer.loadPersistentStores { description, error in
if let error = error {
print("Unable to initialize Core Data \(error)")
}
}
}
}
@main
struct FooAppApp: App {
var body: some Scene {
WindowGroup {
ContentView().environment(\.managedObjectContext, CoreDataManager.shared.context)
}
}
}
当我尝试访问它时,它是我的 ContentView,如下所示:
struct ContentView: View {
@FetchRequest(entity: MyList.entity(), sortDescriptors: []) var myLists: FetchedResults<MyList>
var body: some View {
Text("Hello, world!")
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我收到以下错误:
A fetch request must have an entity.'
terminating with uncaught exception of type NSException
我是不是漏掉了什么?
更新:我从 FetchRequest 中删除了 MyList.entity() 部分,现在可以使用了。
移除
entity: MyList.entity(),
来自 FetchRequest
我正在尝试使用@FetchRequest 通过CoreData 从SQLite 数据库中获取所有记录。我已经设置了 CoreData 堆栈,如下所示:
class CoreDataManager {
private let persistentContainer: NSPersistentContainer
static let shared = CoreDataManager()
var context: NSManagedObjectContext {
return persistentContainer.viewContext
}
private init() {
persistentContainer = NSPersistentContainer(name: "FooModel")
persistentContainer.loadPersistentStores { description, error in
if let error = error {
print("Unable to initialize Core Data \(error)")
}
}
}
}
@main
struct FooAppApp: App {
var body: some Scene {
WindowGroup {
ContentView().environment(\.managedObjectContext, CoreDataManager.shared.context)
}
}
}
当我尝试访问它时,它是我的 ContentView,如下所示:
struct ContentView: View {
@FetchRequest(entity: MyList.entity(), sortDescriptors: []) var myLists: FetchedResults<MyList>
var body: some View {
Text("Hello, world!")
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我收到以下错误:
A fetch request must have an entity.'
terminating with uncaught exception of type NSException
我是不是漏掉了什么?
更新:我从 FetchRequest 中删除了 MyList.entity() 部分,现在可以使用了。
移除
entity: MyList.entity(),
来自 FetchRequest