SwiftData confusing crash

Hi, Developers. The project I am working on includes SwiftData for storing information. When inspecting, code-wise everything looks as it should, however, sometimes when interacting with data, the app crashes. The confusing part is that it happens sometimes. On one simulator, it might crash, while on another it might not. Should I reinstall the app it seems to be working fine again. Do you have and ideas. Any advice is appreciated. Take care!

Answered by zikomiko in 778736022

I have experienced the same behavior and have added a button to regularly delete the data. I feel that during the development, when the data structure changes frequently, the application becomes buggy. Perhaps this might help you.

func removeStoredData() {
        do {
            try context.delete(model: WorkoutModelItem.self)
        } catch {
            fatalError(error.localizedDescription)
        }
    }

Before you start user testing, for example, in TestFlight, you can disable the button again.

Accepted Answer

I have experienced the same behavior and have added a button to regularly delete the data. I feel that during the development, when the data structure changes frequently, the application becomes buggy. Perhaps this might help you.

func removeStoredData() {
        do {
            try context.delete(model: WorkoutModelItem.self)
        } catch {
            fatalError(error.localizedDescription)
        }
    }

Before you start user testing, for example, in TestFlight, you can disable the button again.

Edit: this is basically an explanation of @zikomiko's solution

Hi! I'm also starting out with SwiftData, but I believe these crashes usually happen when you create significant changes to your app's models.

When you reinstall the app the database is deleted, which makes the new one fully compatible with your newest changes in your model. Do you usually encounter these crashes after modifying your app's models? If yes, these crashes might be caused due to storing old data that is not compatible with your newer version of your model.

Other issues I've encountered were due to using certain types (like SwiftUI Image - it's best to store images as Data with @Attribute(.externalStorage)), but these usually result in build issues.

Thank you! That is a wonderful idea. I can understand that it happens due to the changes, so if it is normally used, they are not that likely to occur.

SwiftData confusing crash
 
 
Q