SwiftUI中带有核心数据关系的全部删除/清除按钮

rvpgvaaj  于 2023-01-16  发布在  Swift
关注(0)|答案(1)|浏览(200)

我想有一个"全部清除"按钮到这个"教室"视图,但我真的不知道如何进行。
首先,下面是我的设置:

// 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)

如果它是一个简单的删除按钮,那么它在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)
}

但是我不知道如何让它在ForEach之外工作,也不知道如何确保每个元素都被删除,而不仅仅是一个!也许,我应该把context.delete(student)放在ForEach里面,但是这感觉不对。
你们怎么做到的?谢谢。

xiozqbni

xiozqbni1#

您可以在CoreDataManager文件中编写一个新函数,该函数接收一个Classroom,然后遍历它的所有Student,删除其中的每一个。
就像这样:

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

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

然后,您可以调用此函数从CoreData中清除教室中的所有学生。

相关问题