In a UIKit-based app where I'm integrating SwiftUI:
class SwiftDataManager {
static let shared = SwiftDataManager()
private init() {}
var container: ModelContainer?
func initializeContainer() {
do {
container = try ModelContainer(for: Cat.self, Dog.self)
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}
}
struct SomeView: View {
@Environment(\.modelContext) var modelContext
...
//list cats and dogs
}
let vc = UIHostingController(rootView: SomeView().environmentObject(SwiftDataManager.shared.container?.mainContext))
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true, completion: nil)
Error on the environmentObject line:
Instance method 'environmentObject' requires that 'ModelContext' conform to 'ObservableObject'
How do I get the modelContext into SomeView so that I can work with the objects saved in SwiftData?