6

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?

SwiftedMind
  • 3,701
  • 3
  • 29
  • 63
  • Can you add details on how the data would be edited ? – Tomtom Jun 26 '23 at 09:01
  • 1
    From anywhere, really. Could be another place in the app (using another context, for example), or on another device through iCloud sync. – SwiftedMind Jun 26 '23 at 09:16
  • 2
    I have not seen anywhere in the docs that show this is possible. What we need is the equivalent of a FetchedResultsController. On top of that I would also like to see updates to an object triggered by a change in a relationship – Joey Slomowitz Jun 29 '23 at 11:04
  • 2
    Observing SwiftData outside of SwiftUI and the fact that @Query is inmutable is quite a limiting. It leaves out any usage ouside SwiftUI like in ViewModels completally outside. – Jan Kubny Jul 20 '23 at 17:01

0 Answers0