SwiftData Fatal error: failed to find a currently active container

I'm new to Apple development and decided to learn using SwiftData and Xcode 15 beta 4 (though I'm starting to think I don't need that extra challenge). I've worked through many issues--with you all's help--but this is one I can't figure out and hasn't shown up in my searches.

I'm working on the traditional task list app (with a Task model). I've tried several approaches to app structure, but each time I eventually hit this same error. It doesn't happen when I set up the new Xcode project, but eventually it does. I've cleaned the build folder, restarted the Simulator, and even rebooted the Macbook I'm working on.

Here's what happens when I click Product > Run:

  • the app builds successfully

  • the Simulator displays a white screen as expected

  • then the error appears.

Here are the error messages:

In the debug area it says:

SwiftData/ModelContainer.swift:159: Fatal error: failed to find a currently active container for Task
Failed to find any currently loaded container for Task)

and in the warning in the editor says Thread 1: Fatal error: failed to find a currently active container for Task

The debugger is highlighting this line in the call stack (not sure if that's useful as a newbie):

#7	0x0000000100bb6d90 in Task.init(id:title:priority:) at /var/folders/3v/q8g4z9bx4lb9z6t7mhgwgghw0000gn/T/swift-generated-sources/@__swiftmacro_10BadgerTool4Task5ModelfMm_.swift:2

Here's the code:

The Task model isn't complex:

//  Task.swift
import Foundation
import SwiftData

@Model
class Task {
    @Attribute(.unique) var id: UUID
    var title: String
    var priority: String
    
    init(id: UUID = UUID(), title: String, priority: String = "None") {
        self.id = id
        self.title = title
        self.priority = priority
    }
}

I have the model container set in the context of the highest view:

//  BadgerToolApp.swift
import SwiftUI
import SwiftData

@main
struct BadgerToolApp: App {
    var body: some Scene {
        WindowGroup {
            NavView()
            .modelContainer(for: Task.self)
        }
    }
}

I tried moving all other views one layer down (which is why the unnecessary NavView is there):

//  NavView.swift
import SwiftUI
import SwiftData

struct NavView: View {
    @State var selectedCollection: Collection?
    @State var selectedTask: Task?
    
    var body: some View {
        NavigationSplitView(
            sidebar: {
                SideBarView(selectedCollection: $selectedCollection, selectedTask: $selectedTask)
            },
            content: {
                ContentListView(selectedCollection: $selectedCollection, selectedTask: $selectedTask)
            },
            detail: {
                TaskDetailView(selectedCollection: $selectedCollection, selectedTask: $selectedTask)
            }
        )
    }
}

Trying to isolate my mistake

I removed everything else related to SwiftData (except for the imports) and gave my views hard-coded data for the simulator like this:

//  SideBarView.swift
import SwiftUI
import SwiftData

struct SideBarView: View {
    @Binding var selectedCollection: Collection?
    @Binding var selectedTask: Task?
    let collections = presetCollections //temp data

    var body: some View {
            List(collections, id: \.id, selection: $selectedCollection){ collection in
                NavigationLink(collection.name, value: collection)
            }
            List{
                Text("All Tasks")
                Text("Settings")
            }
            .navigationTitle("Collections")
    }

}

Everything works as expected if

  • I comment out the .modelContainer() modifier on the call to NavView view
  • I change the Task definition from the @Model class to a regular struct like this:
//  Task.swift
// with @Model removed

import Foundation

struct Task: Hashable {
    var id: UUID
    var title: String
    var priority: String
    
    init(id: UUID = UUID(), title: String, priority: String = "None") {
        self.id = id
        self.title = title
        self.priority = priority
    }
}

What am I missing? Could it be a bug?

Thanks for your help!

Accepted Reply

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)
    }
}
  • This solution no longer works for me in Xcode 15 beta 5.

Add a Comment

Replies

Yeah, I had the same issue myself. When the model is created, the app crashes as it can't find an available CloudKit container. If you have CloudKit enabled, it requires all properties to be optional. Making all properties and relationships optional fixed the issue for me.

  • This, and deleting any @Attribute(.unique) did it for me (AFAIK, iCloud doesn't support Unique constraints).

Add a Comment

Could you show the file where the ModelContainer was set up? That would help find the issue.

I found that it works in a simulator, but not on an iPhone or the preview(might be a beta bug). Here is my code:

import SwiftUI
import SwiftData

struct DiscoverView: View {
    
    @Environment(\.modelContext) private var context
    @Query private var rootBeers: [RootBeerData]
    var body: some View{
        NavigationStack{
            List(rootBeers) { rootbeer in
                discoverSumary(title: rootbeer.name, desc: rootbeer.desc, icon: rootbeer.icon)
            }
            .navigationTitle("Discover")
            .listStyle(.inset)
        }
    }
}

#Preview {
    DiscoverView()
}

And this is the data model:

import Foundation
import SwiftData
import SwiftUI

@Model
class RootBeerData{
    var name: String
    var desc: String
    var icon: String
    
    init(name: String, desc: String, icon: String) {
        self.name = name
        self.desc = desc
        self.icon = icon
    }
}

And don't forget to add the .modelContainer(for: RootBeerData.self) modifier to ContentView()

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")
        })
    }
}

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)
    }
}
  • This solution no longer works for me in Xcode 15 beta 5.

Add a Comment

Thanks, that seems to do it.

The other solution—and the one I’m least happy with—is to completely delete the app and its data from the simulator and restart the simulator. I still can’t make the error happen reliably, so it’s hard to call it a bug.

Thanks for all your help!

  • I have the same issue with 15.5, but only my M1 Mini. No crashes on the M1 MBAir - identical code (via iCloud). I have tried all the solutions posted here except yours. How do you delete the app and its data from the Simulator?

  • I have managed to resolve this issue - Coding with Chris https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwiCn_TQt8iAAxUK2aQKHVg7Ay4Qz40FegQIDRAq&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D13QubFwmDoc&usg=AOvVaw2wD_81c6o2fokgREzx_tZC&opi=89978449

  • Delete an app just like a regular iPhone: Hold down the app icon until it asks if you want to remove the app (yes) and then ask if you want to remove all the data (yes)

Add a Comment

I had the same issue after the XCode beta 5 update.

My issue has three models in an array, so a slightly different solution:

import SwiftData import SwiftUI

@main struct SurvAIApp: App {

let modelContainer: ModelContainer

init() {
	do {
		modelContainer = try ModelContainer(for: [ViewModel1.self,ViewModel2.self, ViewModel3.self])
	} catch {
		fatalError("Could not initialize ModelContainer")
	}
}
var body: some Scene {
    WindowGroup {
        NavigationStack {
            ContentView()
        }
        .modelContainer(modelContainer )

    }
}
  • Works like a charm. Thanks!

Add a Comment

I had this issue after a change in the model. In my case, removing the app and re-installing did the trick.

  • it worked for me thanks!

Add a Comment

I face the same issue in modifying my initial model and trying to insert data with additional values. I believe SwiftData requires a migration of schema after this but a simple solution for me was to delete the app and let XCode recreate it on both simulator and iPhone.