Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create ModelContainer for SwiftData on iCloud

I have two following models created in my SwiftData project in Xcode

@Model
class Notebook {

    var id: String = ""
    var name: String = ""
    var desc: String?
    var notes: [Note]?

    init(id: String, name: String, desc: String? = nil) {
        self.id = id
        self.name = name
        self.desc = desc
    }
}

and

@Model
class Note {
    var id: String = ""
    var created: Date = Date()
    var updated: Date?
    var text: String = ""
    var notebook: Notebook  

    init(id: String, created: Date, updated: Date? = nil, text: String, notebook: Notebook) {
        self.id = id
        self.created = created
        self.updated = updated
        self.text = text
        self.notebook = notebook
     }
}

Project is compiled and works fine if CloudKit capability is unchecked but when I allow it and assign container on iCloud then it fails with error

Fatal error: Could not create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer)

I tried to make notebook property in Note model optional but it didn't help.

Code for ModelContainer creation

var sharedModelContainer: ModelContainer = {
    let schema = Schema([Notebook.self, Note.self])
    let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

    do {
        return try ModelContainer(for: schema, configurations: [modelConfiguration])
    } catch {
        fatalError("Could not create ModelContainer: \(error)")
    }
}()

I'll be grateful for advice. Thanks.

like image 746
Dawy Avatar asked Mar 10 '26 22:03

Dawy


1 Answers

I could resolve a similar problem by deleting and reinstallimg the app on the device. This was probably because the existing app had an old model instead of its updated version.

like image 129
Lalit Patel Avatar answered Mar 14 '26 23:03

Lalit Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!