I have a simple example. I fetch all Trip
objects from my database:
import SwiftData
@Model
class Trip {
var name: String
}
func fetch() {
let container = ModelContainer(for: Trip.self)
let context = ModelContext(container)
let fetchDescriptor = FetchDescriptor<Trip>()
let trips = try! context.fetch(fetchDescriptor)
// Store it somewhere ...
}
How do I observe changes to the trips array? I know that the individual objects inside the array are observable and will change when something is committed to the database. However, what if the order changes, or some trip is deleted or new ones are inserted? I cannot find a mechanism to get notified of this.
The only way I found was using the new @Query
property wrapper in SwiftUI. But I want to observe changes outside the SwiftUI environment, in separate classes. Is there a way to do this?