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

< How to add Core Data objects from SwiftUI views   How to preview your layout at different Dynamic Type sizes >

How to delete Core Data objects from SwiftUI views

Deleting Core Data objects in SwiftUI is mostly the same as deleting them in UIKit, although there are a couple of special hoops to jump through to integrate with SwiftUI’s views.

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

Once you have your managed object context, make it available to your SwiftUI view as a property like this one:

@Environment(\.managedObjectContext) var managedObjectContext

Next, create a fetch request that reads some data from your managed object context. In my example setup there’s a ProgrammingLanguage entity, so we can read out all items like this:

@FetchRequest(
    entity: ProgrammingLanguage.entity(),
    sortDescriptors: [
        NSSortDescriptor(keyPath: \ProgrammingLanguage.name, ascending: true),
    ]
) var languages: FetchedResults<ProgrammingLanguage>

Third, add an onDelete modifier to your SwiftUI view, wherever you’re showing your data. For example, using the above fetch request you might create a list using ForEach, like this:

List {
    ForEach(languages, id: \.self) { language in
        Text("Creator: \(language.creator ?? "Anonymous")")
    }.onDelete(perform: removeLanguages)
}

Finally, add the removeLanguages() method to your SwiftUI view. This should accept an IndexSet, which is a collection of unique integer indexes that should be deleted:

func removeLanguages(at offsets: IndexSet) {
    for index in offsets {
        let language = languages[index]
        managedObjectContext.delete(language)
    }
}

You might want to save your Core Data context at this point, in which case after the for loop finishes add something like this:

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

Just adding an onDelete modifier is enough to get swipe to delete on your table rows, but if you also want an Edit/Done button to toggle editing mode you should add this modifier to whatever is directly inside your NavigationView:

.navigationBarItems(trailing: EditButton())

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 add Core Data objects from SwiftUI views   How to preview your layout at different Dynamic Type sizes >
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!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>