Skip to main content

How to add Core Data objects from SwiftUI views

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to add Core Data objects from SwiftUI views 관련

SwiftUI by Example

Back to Home

How to add Core Data objects from SwiftUI views | SwiftUI by Example

How to add Core Data objects from SwiftUI views

Updated for Xcode 15

Saving Core Data objects in SwiftUI works in exactly the same way it works outside of SwiftUI: get access to the managed object context, create an instance of your type inside that context, then save the context when you’re ready.

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

Anywhere you need to create Core Data objects you should add an @Environment property to ContentView to read the managed object context right out:

@Environment(\.managedObjectContext) var managedObjectContext

Next, go ahead and create an instance of your Core Data entity class wherever you need, referencing that managedObjectContext. In my example setup, we have a ProgrammingLanguage entity with name and creator properties, so we could create one of those inside a SwiftUI button action like this:

Button("Insert example language") {
    let language = ProgrammingLanguage(context: managedObjectContext)
    language.name = "Python"
    language.creator = "Guido van Rossum"
    // more code here
}

Finally, save the context whenever is appropriate – that might be immediately, after a group of objects have been added, when the state of your app changes, and so on.

If you’re using my PersistenceController setup code from earlier, replace // more code here with this:

PersistenceController.shared.save()

If you’re not, use this code instead:

do {
    try managedObjectContext.save()
} catch {
    // handle the Core Data error
}

Remember, for general saves that don’t directly follow creating a new object, it’s usually worth adding a check to see whether your managed object context has any changes:

if managedObjectContext.hasChanges {
Similar solutions…
How to delete Core Data objects from SwiftUI views | SwiftUI by Example

How to delete Core Data objects from SwiftUI views
Observable objects, environment objects, and @Published | SwiftUI by Example

Observable objects, environment objects, and @Published
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared
How to use @StateObject to create and monitor external objects | SwiftUI by Example

How to use @StateObject to create and monitor external objects
How to use @ObservedObject to manage state from external objects | SwiftUI by Example

How to use @ObservedObject to manage state from external objects

이찬희 (MarkiiimarK)
Never Stop Learning.