UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Thread 1: "executeFetchRequest:error: A fetch request must have an entity."

Forums > SwiftUI

When I run my project file it gets the error in the @main file as it is in the title. I don't really know what's causing it but I wanna know why this is happening or what it means. I don't find any other errors exept for this, but at the same time I get the purple warnigs of "Accessing StateObject's object without being installed on a View. This will create a new instance each time." on those lines of code:

    class DataController: ObservableObject {
        @FetchRequest(sortDescriptors: []) var finance: FetchedResults<Finance>

        var currencyUsd: [Finance] {
            finance.filter { $0.currency == "USD"}         // here it gets the purple warnig
        }
        var currencyMxn: [Finance] {
            finance.filter { $0.currency == "MXN"}
        }
        var currencyJpy: [Finance] {
            finance.filter { $0.currency == "JPY"}
        }
        var currencyEur: [Finance] {
            finance.filter { $0.currency == "EUR"}
        }

        let container = NSPersistentContainer(name: "Finance")

        init() {
            container.loadPersistentStores { description, error in
                if let error = error {
                    print("Core Data failed to load: \(error.localizedDescription)")
                }
            }
        }
    }

    class DataControllerIncome: ObservableObject {
        let container = NSPersistentContainer(name: "Income")

        init() {
            container.loadPersistentStores { description, error in
                if let error = error {
                    print("Core Data failed to load: \(error.localizedDescription)")
                }
            }
        }
    }

2      

You need to pass an entity reference that you want fetched. If you imagine that you have several entities defined in your CoreData, you have to tell the function which one contains the data you are after.

You have not shown your entity definitions (your CoreData setup), but I guess that you have an entity Finance, and that is where the FetchRequest should look for the data.

@FetchRequest(entity: Finance.entity(),  sortDescriptors: []) var finance: FetchedResults<Finance>

3      

Go to your @main class

and add this line

@StateObject var dataController = DataController.shared , and then use this to create managedObjectContext and add it to environment, hope it helps

3      

your data controller

@MainActor
class DataController: ObservableObject {
    static let shared = DataController()
    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "YourData")
        if inMemory {
            container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        }

        container.loadPersistentStores { descriptions, error in
            if let error = error {
                fatalError("failed to load data store \(error)")
            }

        }
    }

    func save() {
        if container.viewContext.hasChanges {
              try? container.viewContext.save()
        }
    }

    func delete(obj: NSManagedObject) {
        container.viewContext.delete(obj)
    }

}

your @main class

@main
struct demoApp: App {
    @StateObject var dataController =  DataController.shared

    var body: some Scene {
        WindowGroup {
            ContentView(data: dataController)
                .environment(\.managedObjectContext, dataController.container.viewContext)
        }
    }
}

3      

@Greenamberred @AmitShrivastava Thank you for your answers. I tried those solutions but I didn't seem like working. When I add the @StateObject var dataController = DataController.shared , I got an error like this one: Type 'DataController' has no member 'shared'

2      

You need to add this line in your datacontroller class - static let shared = DataController() , its nothing but a way to reference a class with out creating its instance ...

2      

Also just one more suggestion, if you are making a navigational jump and reaching your main View which can be ContentView() , make sure to add the environment object there as well, as if the context is not available then also such purple error show up, so make sure the DataController is a stateobject and also to add the environmentobject where ever you are navigating to contentview

ContentView(data: dataController)
                .environment(\.managedObjectContext, dataController.container.viewContext)

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.