glob
glob

Reputation: 310

Fetching data from a Core Data entity using relationships

I have two entities in my core data model, Computer and Components. A computer can have multiple components, so the relationship is set as to-many. Computer also has an attribute computerName.

When adding a component I want the selected computer to appear in the add component view. This add component view is written in SwiftUI and I have this code to create the ManagedObjectContext and to fetch the computer object:

    @Environment(\.managedObjectContext) var moc: NSManagedObjectContext
    @FetchRequest(entity: Computer.entity(), sortDescriptors: []) var computerToDisplay: FetchedResults<Computer>

I then run the following ForEach loop which I would expect to it to grab a Computer and place it in the Text field

    ForEach(computerToDisplay, id: \.self) { computer in
        Text(computer.computerName)
    }

With this code, when I attempt to open the add component view I get the following error:

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

Now, I'm loading the add component view from a UIKit ViewController. So I'm not sure if something isn't getting passed through to the add component view.

This is how I'm loading the component view:

@IBSegueAction func addComponentSegueAction(_ coder: NSCoder) -> UIViewController? {
    let swiftUIView = UIHostingController(rootView: AddComponentView().environment(\.managedObjectContext, moc!))
    present(swiftUIView, animated: true, completion: nil)
    return UIHostingController(coder: coder, rootView: AddComponentView())
}

Any help would be greatly appreciated, thank you.

Upvotes: 0

Views: 219

Answers (1)

Karthick Selvaraj
Karthick Selvaraj

Reputation: 2505

Try this,

@IBSegueAction func addComponentSegueAction(_ coder: NSCoder) -> UIViewController? {
    let swiftUIView = UIHostingController(coder: coder, rootView: AddComponentView().environment(\.managedObjectContext, moc!)
    return swiftUIView
}

Seems, you are creating multiple instances of UIHostingViewController with your AddComponentView() and returning the one which don't have AddComponentView() managedObjectContext in environment.

Thanks!

Upvotes: 1

Related Questions