Skip to main content

How to access a Core Data managed object context from a SwiftUI view

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to access a Core Data managed object context from a SwiftUI view 관련

SwiftUI by Example

Back to Home

How to access a Core Data managed object context from a SwiftUI view | SwiftUI by Example

How to access a Core Data managed object context from a SwiftUI view

Updated for Xcode 15

If you followed my Core Data and SwiftUI set up instructions, you’ve already injected your managed object context into the SwiftUI environment.

If not, make sure you add this code to your scene delegate:

ContentView()
    .environment(\.managedObjectContext, yourCoreDataContext)

That passes our view context directly into ContentView as environment data, which means we can add an @Environment property to ContentView to read the managed object context right out:

@Environment(\.managedObjectContext) var managedObjectContext

Note

Adding a local property for the managed object context isn’t required for performing fetch requests using @FetchRequest – you only need it for saving, deleting, and some other tasks.

Similar solutions…
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to show a context menu | SwiftUI by Example

How to show a context menu
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared
How to convert a SwiftUI view to an image | SwiftUI by Example

How to convert a SwiftUI view to an image
How to delete Core Data objects from SwiftUI views | SwiftUI by Example

How to delete Core Data objects from SwiftUI views

이찬희 (MarkiiimarK)
Never Stop Learning.