1

I'm encountering an issue where my app crashes when users update to a new version.

I reproduced the error locally and basically it happens when I run the app with the new stored field added to the SwiftData model, but on the previous version of the database (which is exactly what happens upon releasing a new version of the app — users have new code but the database is from the previous version).

I expected SwiftData to handle this change automatically (via lightweight migration) by adding the new field to the database without requiring custom migration code.

Here's an example of the added field (CloudKit is enabled for the app):

final class TodoItem {
    var title = ""
    var content = ""
    var fontName: String = "Times" // <- new field
}

The new field has a default value, so I assumed the migration would be smooth and automatic. However, the app crashes on the first launch after the update but succeeds on subsequent launches.

This is the container setup:

class AppModelSchema {
    static let schema = Schema([
        TodoItem.self
    ])
}

class AppModelContainer {
    static var modelContainer = {
        let schema = AppModelSchema.schema
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch let error {
            Bugsnag.notifyError(error)

            fatalError("Could not create a model container: \(error.localizedDescription)")
        }
    }()

    @MainActor
    static var modelContext: ModelContext {
        modelContainer.mainContext
    }
}

How can I resolve this issue and ensure a smooth migration process?

3
  • How do you setup your ModelContainer instance? Commented Jul 12, 2024 at 20:16
  • @JoakimDanielson Added the contaner setup code. Basically, it's the standard one. Commented Jul 15, 2024 at 16:07
  • Yes that looks quite standard. I guess CloudKit is part of the issue then, unfortunately I don’t have much to contribute with when it comes to SwiftData and CloudKit Commented Jul 15, 2024 at 21:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.