WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

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      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.