Model Container
- An object that manages an app’s schema and model storage configuration.
- Model Container is set in WindowGroup. We can pass multiple data models over there.
@main
struct SwiftData_ExampleApp: App {
var body: some Scene {
WindowGroup {
NavigationStack {
UserList()
}
}
.modelContainer(for: [User.self, Company.self])
}
}
ModelContext
- An object that enables you to fetch, insert, and delete models, and save any changes to disk.
- Everything in SwiftData happens with model context.
- It is basically like view context in CoreData.
@Environment(\.modelContext) private var modelContext
Query
- Use
@Query in your SwiftUI views to fetch data.
- SwiftData and SwiftUI work together to provide live updates to your views when the underlying data changes, with no need to manually refresh the results.
- You can add predicate to the query to filter the elements, sort the query, set the order- whether to sort in forward or reverse order and set animation for user interface changes that result from changes to the fetched results.
Click Here