1

I am trying to delete multiple core data at the same time using the selection in edit mode. However, the row is not getting deleted. I'm not sure what the problem is.

What I have tried was adding id:\.id or id:\.self on the ForEach(notes)

What is the problem with my code? Is there any other way to delete multiple rows?

struct TempNoteView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(sortDescriptors: [],animation: .default)
    private var notes: FetchedResults<Note>
    
    @State var editMode: EditMode = .inactive
    @State var selection = Set<UUID>()

    var body: some View {
        List(selection: $selection) {
            ForEach(notes) { note in
                    NavigationLink(destination: NoteView(note: note)) {
                        Text(note.name ?? "Untitled")
                        Spacer()

                        Button(action: {
                            if note.pin == false {
                                note.pin = true
                                saveContext()
                            } else {
                                note.pin = false
                                saveContext()
                            }
                        }) {
                            if note.pin {
                                Image("pinned").resizable().frame(width: 23, height: 23, alignment: .center)
                                .padding(.trailing, 10)
                            } else {
                                Image("not-pinned").resizable().frame(width: 23, height: 23, alignment: .center)
                                .padding(.trailing, 10)
                            }
                        }.buttonStyle(PlainButtonStyle())
                        
                    }
                    .padding()
                    .listRowInsets(EdgeInsets())
//                    .listRowBackground(Color.gray.opacity(0.1))
                    .background(Color.yellow.opacity(0.3))
                    .clipShape(RoundedRectangle(cornerRadius: 10))
                    .listStyle(SidebarListStyle())
                    .padding(.init(top: 10, leading: 0, bottom: 10, trailing: 0))
                    
                }.onDelete(perform: deleteNotes)
            }
            .environment(\.editMode, self.$editMode)
            .navigationTitle("Notes")
            .navigationBarItems(
                leading:
                    HStack {
                        editButton
                        deleteButton
                    },
                trailing: Button(action: {addNote()}, label: {
                Text("Add Note")
                Image("plus")
            })).onAppear(){
                UITableViewCell.appearance().selectionStyle = .none
            }
            
    }
    private var editButton: some View {
        if editMode == .inactive {
            return Button(action: {
                self.editMode = .active
                self.selection = Set<UUID>()
            }) {
                Text("Edit")
            }
        }
        else {
            return Button(action: {
                self.editMode = .inactive
                self.selection = Set<UUID>()
            }) {
                Text("Done")
            }
        }
    }
    
    private var deleteButton: some View {
        if editMode == .inactive {
            return Button(action: {}) {
                Image("")
            }
        } else {
            return Button(action: deleteAllNotes) {
                Image(systemName: "trash")
            }
        }
    }
    
    private func deleteAllNotes() {
        for id in selection {
            if let index = notes.lastIndex(where:{ $0.id == id }) {
                viewContext.delete(notes[index])
            }
        }
        selection = Set<UUID>()
    }
    
    
    func saveContext() {
        do {
            try viewContext.save()
        } catch {
            let error = error as NSError
            fatalError("Unresolved Error: \(error)")
        }
    }
    
    private func deleteNotes(offsets: IndexSet) {
        withAnimation {
            offsets.map { notes[$0] }.forEach(viewContext.delete)
            saveContext()
        }
    }
    
    private func addNote() {
        withAnimation {
            let newNote = Note(context: viewContext)
            newNote.id = UUID()
            newNote.name = "New Note"
            newNote.createdAt = Date()
            newNote.pin = false
            saveContext()
            
        }
    }
}

1 Answer 1

1

Change your ForEach to

ForEach(notes, id:\.self) { note in

then change the Set to take Notes as type

@State var selection = Set<Notes>()

And then inside your deleteAllNotes (which I would rename to deleteAllSelectedNotes) delete every selected note.

private func deleteAllNotes() {
    for item in selection {
        viewContext.delete(item)
    }
    selection = Set<Note>()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.