hi Gerry,
i took Stepan's question to mean that there might be (class) objects out there in an app that need to know about the modelContext. if that's the case, the suggestion i gave above certainly makes it possible.
there is another alternative situation, such as what you see in an MVVM-style app, where when a SwiftUI view is instantiated, it creates a view model and passes it the modelContext.
in both cases, that non-View (class) object is then able to make ad-hoc data fetches against SwiftData using the modelContext.
but perhaps you're looking at something a little different: the idea of a (class) object having its own version of a @Query
, so that it can monitor changes in the modelContext.
if we were using Core Data, such a (class) object would use an NSFetchedResultsController
(rather than a @FetchRequest that can only be used in a View) to monitor changes in the modelContext in real time.
that is, @FetchRequest is designed to easily work with Core Data, but only in a View. an NSFetchedResultsController provides pretty much the same function, although you can use it anywhere you like.
so i think you're asking "if @Query is designed to easily work with SwiftData, but only in a View, what provides the same functionality everywhere else?
alas, the answer right now for SwiftData is: nothing. (in fact, if you look at the sample project i suggested above, you'll see that the one object i created outside of SwiftUI with access to the modelContext has to be told to make a new data fetch whenever i change the number of items on the shopping list -- it is not capable of discovering the change on its own.)
look to WWDC2024 and "SwiftData 2" to fill this gap. (is it really only three months away?) i would think this is one of the most obvious additions for SwiftData.
hope that helps,
DMG