Post

Replies

Boosts

Views

Activity

Reply to SwiftData Fatal error: failed to find a currently active container
I was trying to test this and am getting the error if I initialize the item in the View. Works fine if I initialize the model in the view's .onAppear. I am not knowledgeable on this subject, but could it be that the container is not ready yet until the view appears? Or I might be using this wrong to beging with... Doesn't work: struct ContentView: View { @Environment(\.modelContext) private var modelContext @State var item: Item? init() { freezer = Item(name: "My Item") } var body: some View { Text(item?.name ?? "No item") } } Works: struct ContentView: View { @Environment(\.modelContext) private var modelContext @State var item: Item? var body: some View { Text(item?.name ?? "No item") .onAppear(perform: { item = Item(name: "Test Item") }) } }
Jul ’23
Reply to SwiftData Fatal error: failed to find a currently active container
I do really think the container is not correctly initiated yet at that point? Initializing the container prior to passing it in seems to fix it, like so: @main struct MyApp: App { let modelContainer: ModelContainer init() { do { modelContainer = try ModelContainer(for: Item.self) } catch { fatalError("Could not initialize ModelContainer") } } var body: some Scene { WindowGroup { ContentView() } .modelContainer(modelContainer) } }
Jul ’23