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?
Notice how you read the model context in a SwiftUI view:
You use the overload of
@Environmentthat takes anEnvironmentValueskey path. You do not use@EnvironmentObjectto access the model context, do you?So in the same way, you use the
.environmentmodifier that takes anEnvironmentValueskey path to set the model context.I'm not sure why your
containerhere is optional. You should decide what to do when it is nil.