Contents

ResultsObserver

Observes and tracks changes to a collection of persistent models in a model context.

Declaration

final class ResultsObserver<Element, SectionName> where Element : PersistentModel, SectionName : Hashable

Overview

ResultsObserver automatically monitors changes to models that match specified fetch criteria, providing real-time updates when the underlying data changes. The observer maintains a collection of fetched results, making it ideal for keeping user interfaces synchronized with persistent data.

The observer responds to changes from multiple sources:

  • Local changes made within the same model context

  • Remote changes from other contexts within the same container

  • External changes from other processes or CloudKit sync

You can configure the observer using either a complete FetchDescriptor or individual filter predicates and sort descriptors. The observer is Observable, allowing SwiftUI views to automatically update when results change.

Use Never as the SectionName type parameter when no sectioning is needed:

let observer = try ResultsObserver<Book, Never>(
    filterBy: #Predicate { $0.isPublished },
    sortBy: [SortDescriptor(\.title)],
    modelContext: context
)

Use a concrete type (e.g. String) when sectioning by a key path of that type:

let observer = try ResultsObserver<Book, String>(
    sectionBy: \.genre,
    modelContext: context
)

Topics

Creating a results observer with a fetch descriptor

Creating a results observer with a predicate

Accessing observer properties

Accessing observer results

See Also

Data store observation