Logo for tanaschita.com

How to get a SwiftData model container and context in SwiftUI

Learn how to setup a SwiftData container and context directly in SwiftUI.

30 Oct 2023 · 4 min read

At WWDC23, Apple introduced SwiftData - a framework which focuses on persisting data by using declarative code. In this overview on SwiftData for iOS, we already looked at the basics of SwiftData.

In this article, we'll look at view modifiers which we can use to setup a SwiftData container and context directly in SwiftUI.

Let's get started.

Sponsorship logo
Preparing for a technical iOS job interview - updated for iOS 17
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
LEARN MORE

In the previous article, we already learned on how to setup a SwiftData model container:

let modelContainer = try ModelContainer(for: [User.self])

When working with SwiftUI, we can alternatively use the modelContainer view modifier as follows:

struct ExampleApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: [User.self])
}
}

The example above creates a container for the whole window groupe scene. The window and its views will inherit the container.

If a view needs its own container, we can setup one in the same way by applying the modelContainer modifier to a specific view. Changes to one container won't affect another container.

When we setup the model container through the view modifier as shown above, it makes the model context available through the application's environment:

@Environment(\.modelContext) private var context

We can use the environment to get the model context in any SwiftUI view we need.

Sponsorship logo
Preparing for a technical iOS job interview - updated for iOS 17
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

swiftdata

persistence

swiftui

swift

ios

Quick developer guide on SwiftData for iOS

Get an overview on Apple's SwiftData framework.

16 Oct 2023 · 4 min read

Latest articles and tips

© 2024 tanaschita.com

Privacy policy

Impressum