Repeated SwiftData error in finding currently active container

Hello everybody, I am a German math student trying to build some super simple educational apps. I always run into the same problem:

Error message: Thread 1: Fatal error: failed to find a currently active container for Category

Occurs in the macro Code in the line::

@Transient
private var _$backingData: any SwiftData.BackingData<Category> = Category.createBackingData()

I injected the Container in the Main File:

@main
struct TodointimeApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }.modelContainer(for: Category.self)
    }
}

my Model is pretty easy:

import Foundation
import SwiftData

@Model
class Category {
    var name: String
    var tasks: [TaskModel] = [TaskModel]()
    
    init(name: String, tasks: [TaskModel]) {
        self.name = name
        self.tasks = tasks
    }
    
}



@Model
class TaskModel {
    var title: String
    var datetodo: Date
    var takentime: TimeInterval
    var isdone: Bool
    var category: Category
    
    init(title: String = "Default Task", datetodo: Date = .now, takentime: TimeInterval = 0, isdone: Bool = false, category: Category) {
        self.title = title
        self.datetodo = datetodo
        self.takentime = takentime
        self.isdone = isdone
        self.category = category
    }
}

This occurs in everything that I am trying to do and I just can't figure out what's wrong. I would be super grateful about some tips.

Thanks in advance.

Did you check the cloudkit box by any chance? It may be looking for something there, I think cloudkit containers want all the vars to be optional

For your var tasks, try removing the () after [TaskModel] and initialize it as an empty array to start. That is what helped me remove this error. Not sure of another work around.

This happened to me on iOS 17.5 (it works fine on iOS 18). What I did was simply initialize the ModelContainer in the @main struct. The odd thing is that I don’t use this container reference anywhere, but it does fix the crash issue.

let container: ModelContainer?

init() {
   do {
       let config = ModelConfiguration(isStoredInMemoryOnly: true)
       container = try ModelContainer(for: Category.self, configurations: config)
   } catch {
       print("Failed to initialize ModelContainer: \(error)”)
       container = nil
   }
}