I am the author of Core Data Fundamentals with Swift, CloudKit, iOS Data Persistence: The Big Picture, and eight other courses on Pluralsight.
Deepen your understanding by watching the courses!
How to Pass NSManagedObjectContext to a SwiftUI View
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
AppDelegate
. - Code examples are taken from my “Blog Idea List” sample project that includes a single Core Data Entity named
BlogIdea
:
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
@Environment
’smanagedObjectContext
variable.
“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.
SceneDelegate.swift
|
|
ContentView.swift
|
|
For a more complete guide to using Core Data with SwiftUI, you can refer to the introduction I published. It includes an example project with all of the pieces stitched together!