Home > Software engineering >  Delete/clear all button with Core Data Relationships in SwiftUI
Delete/clear all button with Core Data Relationships in SwiftUI

Time:01-16

I'd like to have a "Clear all" button into this "Classroom" view but I really don't know how to proceed.

First, here're my settings below:

// ClassroomView.swift
import SwiftUI

struct ClassroomView: View {

    @Environment(\.managedObjectContext) private var viewContext
    var classroom: FetchedResults<Classroom>.Element

    var body: some View {
        ScrollView {
            VStack {
                // Some Code Here
                Button("classroom-button-clear", action: { /* What to write here? */ })
                // Some Code Here
                ForEach(classroom.studentArray) { student in
                    StudentView(student: student)
                    Divider()
                }
                // Some Code Here
            }
        }
    }
}

struct StudentView: View {

    var student: FetchedResults<Student>.Element

    var body: some View {
        HStack {
            Text(student.date!)
            Spacer()
            Text(student.name!)
        }
    }
}

extension Classroom {
    public var studentArray: [Student] {
        let set = student as? Set<Student> ?? []
        return set.sorted {
            $0.date! > $1.date!
        }
    }
}
// ClassroomModel.xcdatamodeld

// Entity 1: Classroom (id, date, title, etc...)
     // Relation: student - Student - classroom (To Many)

// Entity 2: Student (id, date, name, etc...)
    // Relation: classroom - Classroom - student (To One)

If it was a simple delete button, it could be something like this inside the ForEach(classroom.studentArray):

// StudentView.swift
Button("student-button-clear", action: {
    CoreDataManager.shared.deleteStudent(student: student, context: viewContext)
})

// CoreDataManager.swift
func deleteStudent(student: student, context: NSManagedObjectContext) {
    context.delete(student)
    save(context: context)
}

But I don't know how to make it works outside the ForEach and also make sure every elements are deleted and not just one! Maybe, I should place context.delete(student) inside a ForEach too but this doesn't feel right.

How do you guys do that? Thanks.

CodePudding user response:

You can write a new function inside the CoreDataManager file that receives a Classroom and, iterating through all of its Students, deletes each one of them.

Like this:

func deleteStudentsForClassroom(_ classroom: Classroom, context: NSManagedObjectContext) {

    classroom.studentArray.forEach {
        context.delete($0)
    }
    save(context: context)
}

You can then call this function to erase all students of the classroom from CoreData.

  • Related