Search code examples
iosswiftswiftuiswiftdata

SwiftData crashes app on get value: Thread 1: EXC_BREAKPOINT (code=1, subcode=0x101e8303c)


I'm utilizing SwiftData in my app, and I have a Tracker model with two variables: name of type String and trackerType of type TrackerType, which is another model. Retrieving name data from the Tracker works fine, but attempting to read trackerType results in a crash with the error:

EXC_BREAKPOINT (code=1, subcode=0x101e8303c).

Here's my Tracker Model:

@Model
class Tracker {
    var name: String
    var trackerType: [TrackerType]

    init(name: String, trackerType: [TrackerType]) {
        self.name = name
        self.trackerType = trackerType
    }
}

@Model
class TrackerType {
    var type: String
    var status: Bool

    init(type: String, status: Bool) {
        self.type = type
        self.status = status
    }
}

And the crash result snippest: Crash

I don't understand what could be the issue. I attempted to create the model with dummy data locally in my application.


Solution

  • After dedicating the entire day to investigating, I've identified the root cause of the error.

    The issue lies in the inability to read model data without prior saving it in the SwiftData container. Therefore, the necessary steps are as follows:

    • Avoid using the locally created dummy data model directly.
    • Initially, save the data in the container.
    • Retrieve and use the data from the container.

    So, my code after following those steps is like below:

    import SwiftUI
    import SwiftData
    
    struct DashboardView: View {
        @Environment(\.modelContext) private var modelContext
        @Query private var items: [TrackerItem]
        @AppStorage("DataSaved") private var isDummyDataSavedOnce = false
    
        var body: some View {
            NavigationStack {
                if isDummyDataSavedOnce, let item = items.first  {
                    TrackerView(prayers: item.tracker)
                }
            }
            .onAppear {
                saveDummyData()
            }
        }
    
        private func saveDummyData() {
            if !isDummyDataSavedOnce {
                withAnimation {
                    let newItem = TrackerDummyData.trackerItem
                    modelContext.insert(newItem)
                    isDummyDataSavedOnce.toggle()
                }
            }
        }
    }