Fetching and manipulating our data using model context
Developers familiar with Core Data are also familiar with the idea of context. Context is our data sandbox. This is the place where we can manipulate and fetch data, and it’s the link between our models and the persistent store.
To gain access to our context from our SwiftUI view, we can use an environment variable named modelContext
:
struct ContentView: View { @Environment(\.modelContext) private var modelContext }
The modelContext
environment variable is available whenever we set up our scene using the modelContainer
modifier.
In non-SwiftUI instances, we can access the context using our model container mainContext
property:
let modelContext = modelContainer.mainContext
To understand how to work with a model context, we’ll start with the most basic operation, saving new objects for our store.
Saving new objects
At the beginning of this chapter, in the Defining a SwiftData...