Hi, I started a new project selecting SwiftData as db by default.
I created my models as default.
@Model
class Trip {
var id: UUID
public private(set) var Name: String
public private(set) var Members: [Member]
public private(set) var Buys: [Buy]
public func removeBuy(indexBuyToRemove: Int) {
self.Buys.remove(at: indexBuyToRemove)
}
}
@Model
class Member: Identifiable, Equatable {
var id: UUID
public private(set) var Name: String
}
@Model
class Buy: Identifiable, Equatable {
var id: UUID
public private(set) var Author: Member
public private(set) var Ammount: Double
public private(set) var Title: String
}
I initialize my trips as this in my ContentView
@Query public var tripsList: [Trip]
And then pass this list in every other view.
I also have a ModelContext as default, passed like this in the @Main
@main
struct MainApp: App {
var sharedModelContainer: ModelContainer = {
let schema = Schema([
Member.self, Buy.self, Trip.self
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
.preferredColorScheme(.dark)
}
.modelContainer(sharedModelContainer)
}
}
And defining in the other views like this
@Environment(\.modelContext) var modelContext
Now. For the problem of consistency.
Whenever I add a new Trip I do this or delete (as .onDelete in the List)
public func addTrip(Trip: Trip) {
modelContext.insert(Trip)
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(tripsList[index])
}
}
}
And everything works fine.
The problem starts when I try to delete a Buy element of the Trip.Buys: [Buy]
.
I do like this:
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
let buyToRemove = trip.Buys[index]
trip.removeBuy(indexBuyToRemove: index)
do {
try modelContext.save()
} catch {}
}
}
}
The delete is not consistent. What am I missing? What am I doing wrong?
Thank you for your help