NEW: Learn SwiftUI with my free YouTube video series! >>

< How to filter Core Data fetch requests using a predicate   How to delete Core Data objects from SwiftUI views >

How to add Core Data objects from SwiftUI views

Saving Core Data Objects in SwiftUI 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(action: {
    let language = ProgrammingLanguage(context: self.managedObjectContext)
    language.name = "Python"
    language.creator = "Guido van Rossum"
    // more code here
}) {
    Text("Insert example language")
}

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. To do that, replace // more code here with this:

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

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, like this:

if self.managedObjectContext.hasChanges {

SPONSOR Meet the new Instabug – more than just bug reporting! We help you build better apps and minimize your debugging time. With each bug report, we automatically capture details like network requests, repro steps, and session details. Get real-time crash reports with stack trace details and session data to help you catch and fix issues easily. And with our customizable in-app surveys, you’ll gather insightful user feedback and much more. Instabug is the fastest and easiest way to release with confidence. Start your free trial now! Start your free trial now!

< How to filter Core Data fetch requests using a predicate   How to delete Core Data objects from SwiftUI views >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>