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

How to delete core data items with a button

Forums > SwiftUI

In the BookWorm tutorial this is the function used:

  func deleteTortoise(at offsets: IndexSet) {
        for offset in offsets {
            let tortoise = tortoises[offset]
            moc.delete(tortoise)
        }
        try? moc.save()
    }

How could I use this or simiar to delete using a button in a forEach?

   

Zebs asks an open ended question, without providing a thorough business case.

How could I use this or similar to delete CoreData objects using a button in a ForEach?

This is a multi-level question. Perhaps you want to give an example of your intentions?

Here's a short bit I wrote about thinking of ForEach as a view building factory.

See-> ForEach Button Factory

In summary, you have a collection of some sort. You grind it through a ForEach factory, and SwiftUI will build you a number of views. The views can be Images and Text. The views can be emoji filled strings. The views could be HStacks with Text and Buttons side-by-side. Your choice! Most excellent!

So review your business case. You must have a collection of managed CoreData objects. Call the collection tortoises. The collection is made of one, perhaps many tortoise objects.

Well, it's trivial to run these objects through a ForEach view factory and build custom, cool looking buttons using the data in the tortoise object. That's essentially the job of the ForEach view builder.

I think your question becomes: What is the function each button should perform when tapped? I suppose you want to delete that managed object from the collection? Go for it!

Come back and let us know how you solved this!

   

@Obelix First of all thankyou for your reply!

Here is some more detail:

ForEach loop:

                    ForEach(tortoises, id: \.self) { tortoise in
                        Section(tortoise.unwrappedName) {
                            ForEach(tortoise.hibernationArray, id: \.self) { hibernation in
                                Text("\(hibernation.unwrappedNameH)")
                                        .padding(7)
                                        .background(.blue)
                                        .foregroundColor(.white)
                                        .clipShape(Capsule())
                                HStack{
                                    Text("Start: \(hibernation.unwrappedStart, format: .dateTime.day().month().year())")
                                    Text("End: \(hibernation.unwrappedEnd, format: .dateTime.day().month().year())")
                                    Text("Length: \(hibernation.length) days")
                                   // And for example a button here to delete a hibernation 
                                }
                            }

                        }
                            NavigationLink("Add Hibernation"){
                                AddHibernation( current: tortoise)
                            }
                            // I would like to have a button here to delete the tortoise itself.
                    }

What code do I use to delete said items from core data? When someone clicks the buttons placed where the comments are.

   

Zeb is getting to the heart of CoreData with great questions!

What code do I use to delete said items from core data?
When someone clicks the buttons placed where the comments are.

Zeb: It's great you are digging in to resolve your CoreData questions.

Good Luck!

Good Luck! I hope I didn't make you feel your inital approach was incorrect. I enjoy answering questions and thinking of detailed answers. I enjoy thinking of different ways to explore and explain Swift, design, or architecture concepts that may give new developers heartache. However I've received feedback that my answers are perceived to be condescending, perhaps snarky. I want to remove heartache, not cause it.

I wish you luck on your journey. I will probably be taking a break.

1      

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, 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!

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

Reply to this topic…

You need to create an account or log in to reply.

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.