I am trying to use @FetchRequest to fetch all records from the SQLite database through CoreData. I have setup CoreData stack as shown below:
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)
}
}
}
When I try to access it is my ContentView as shown below:
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()
}
}
I get the following error:
A fetch request must have an entity.'
terminating with uncaught exception of type NSException
Am I missing something?
UPDATE: I removed the MyList.entity() part from the FetchRequest and now it works.
Remove
entity: MyList.entity(),
From the FetchRequest