f16
f16

Reputation: 649

Deleting a related model in cascade when parent is removed causes the app to crash

I understand that relating the Models should simplify data management in the app. I am currently developing an app that allows users to log refuel actions for cars added earlier. The goal is to delete all refuel entries when a respective car is removed. The relationship is one car to many refuel logs.

Unfortunately, it seems that when I remove the car, the app crashes with the Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1cc165d0c). I found a thread that suggests there might be a bug that can be fixed by saving the model after deleting the action. I applied the solution, and the error is resolved, the car is removed, but not the refuel entries. I suspect I am deleting incorrectly or have set up the relationship incorrectly. I have tried various ways to establish the relationship without success.

enter image description here

Car.swift

import Foundation
import SwiftData

@Model
final class Car: Identifiable {
    let id: UUID
    var name: String
    @Relationship(deleteRule: .cascade, inverse: \Refuel.car) var refuels: [Refuel]?
}

Refuel.swift

import Foundation
import SwiftData

@Model
final class Refuel: Identifiable {
  let id: UUID
  @Relationship var car: Car?
  var timestamp: Date

  var volume: Double
  var price: Double
  var cost: Double
}

And this is how I handle cars in the view:

List {
  ForEach(cars, id: \.self) { car in
    NavigationLink {
      CarEditView(car: car)
    } label: {
      CarItemView(car: car)
    }
  }
  .onDelete(perform: deleteItems)
}

Delete action looks like that:

private func deleteItems(offsets: IndexSet) {
  withAnimation {
    for index in offsets {
      modelContext.delete(cars[index])
    }
  }
}

Upvotes: 0

Views: 110

Answers (0)

Related Questions