'SwiftUI: getting error when trying to pass in FetchedRequest data as EnvironmentObject to subView
I have a small app and I am trying to use CoreData to persist items and if it's first launch, they will come from a JSON and get saved to CoreData for all future reloads.
If foods, which comes from fetching CoreData data, has a count of < 1, then that means it's a first time launch and I iterate through the decoded JSON data and save it to CoreData.
I am getting an error when trying to pass the foods into my MainView saying:
Instance method 'environmentObject' requires that 'FetchedResults<Food>' conform to 'ObservableObject'
Any help on what I am doing wrong?
Code:
import SwiftUI
@main
struct myApp: App {
@StateObject private var dataController = DataController()
@State var jsonData: [Food] = Bundle.main.decode("Foods.json")
@FetchRequest(sortDescriptors: []
) var foods: FetchedResults<Food>
init() {
if foods.count < 1 {
let newFood = Food(context: dataController.container.viewContext)
for item in jsonData {
newFood.id = Int16(item.id)
newCountry.isEdible = item.isEdible
newCountry.name = item.name
newCountry.list_names = country.list_names as NSArray
do {
try dataController.container.viewContext.save()
} catch {
let error = error as NSError
print(error)
}
}
}
}
var body: some Scene {
WindowGroup {
MainView()
.environmentObject(foods)
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
