Step one to using Core Data with SwiftUI is to initialize the Core Data stack and pass an instance of your
NSManagedObjectContext to your view.
First Things First
- The remainder of this how-to assumes that you’ve already got a way to initialize the Core Data stack. Ticking the ‘Use Core Data’ checkbox when you start a new app will place some boilerplate code in
- Code examples are taken from my “Blog Idea List” sample project that includes a single Core Data Entity named
You can refer to my introduction to using Core Data with SwiftUI to review all of the steps in one spot. It includes an example project with all of the pieces stitched together!
Breaking Down the Code
There are two key components to this:
- the Core Data Stack
- the SwiftUI
“Passing in” your managed object context will probably happen early on in your app’s launch sequence.
SceneDelegate is where I pass mine in with the Blog Idea List app.
On the receiving end is your SwiftUI View. An
@Environment property wrapper needs to be set up in order to pull out the managed object context so you can use it.
The following code snippets provide you glimpses into both sides of the coin. Comments with ❇️ symbols will explain the details inline.