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:
I don't understand what could be the issue. I attempted to create the model with dummy data locally in my application.
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:
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()
}
}
}
}