Fetching All Trip
Objects From Database
Using the code below, I can 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 ...
}
Observing Changes
I know that the individual objects inside the array are observable and will change when something is committed to the database. However, I need a way to get notified if the order changes, or if some trip is deleted or new ones are inserted.
The only way I found so far is using the new @Query
property wrapper in SwiftUI. Is there a way to observe changes outside the SwiftUI environment, in separate classes?
Yes, you can observe changes to the Trip
objects outside of the SwiftUI environment by using the SwiftData framework’s ModelObserver
class.
Here’s an example of how you can observe changes to the Trip
objects:
import SwiftData
class TripObserver: ModelObserver {
typealias ModelType = Trip
func objectsDidChange(_ objects: [Trip]) {
// Handle the changes to the Trip objects here
}
}
func observeChanges() {
let container = ModelContainer(for: Trip.self)
let observer = TripObserver()
container.addObserver(observer)
}
In the TripObserver
class, you need to conform to the ModelObserver
protocol and specify the ModelType
as Trip
. The objectsDidChange
method will be called whenever there are changes to the Trip
objects.
Then, in the observeChanges
function, you create a ModelContainer
for the Trip
model and add the observer to it using the addObserver
method.
By calling the observeChanges
function, you will start observing changes to the Trip
objects. Whenever there are changes, the objectsDidChange
method in the observer will be called, allowing you to handle the changes accordingly.