UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Core Data delete functionality in Multiplatform swiftUI app

Forums > SwiftUI

@BSM  

Hi,

I am building a multiplatform app that uses core data. I want to add some delete functionality.

When I created the project, apple provided some basic functionality which works for iOS, but not for mac. For deletion on iOS, you would use the .onDelete(perform:) modifier. When I pass in that method that takes in a IndexSet, the modifier passes the indexSet automatically to the method. This is the delete function:

private func deleteItems(offsets: IndexSet) {
        withAnimation {
            offsets.map { items[$0] }.forEach(viewContext.delete)

            do {
                try viewContext.save()
            } catch {
                print(error)
            }
        }
    }

This way of deleting works great on iOS, but MacOS doesn’t have that modifier. It has the onDeleteCommand(perform:) modifier. That modifier triggers a function when the users selects an item, and goes to the menu bar, and selects edit > delete. But, as that modifer doesnt pass in a IndexSet automatically like the onDelete modifier, this doesn’t work.

Is there a way of of getting the indexSet into a (state) variable that will be updated when a user selects an item, which I then could pass into the method when calling the .onDeleteModifier ?

3      

Hey @BSM, not sure if you're still looking to solve this, but SwiftUI's .onDelete() modifier is available on macOS (on Big Sur, at least). It's triggered by swiping on your trackpad, though, so it's effectively non-discoverable.

What I do in WriteFreely (also a multiplatform SwiftUI app) is use a @Published property in an ObservableObject to track what the currently selected post is, and use that in .onDeleteCommand() (see here on GitHub).

Does something like that work for your codebase?

4      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.