为什么一个值变成零

Why a value becomes nil

subject.name 删除一个 topic 后变为 nil

我该如何解决这个问题?

谢谢。

import SwiftUI

struct TopicsView: View {
    @Environment(\.managedObjectContext) var viewContext
    
    let subject: Subject
    
    @FetchRequest(entity: Topic.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Topic.title, ascending: true)]) var topics: FetchedResults<Topic>
    
    @State var title: String = ""
    
    var body: some View {
        Form {
            Section(header: Text("Themen")) {
                ForEach(topics, id: \.self) { topic in
                    if (topic.subject == subject) {
                        NavigationLink(topic.title!, destination: ContentsView(topic: topic)).environment(\.managedObjectContext, viewContext)
                    }
                }
                .onDelete(perform: { indexSet in
                    for index in indexSet {
                        viewContext.delete(topics[index])
                        do {
                            try viewContext.save()
                        } catch {
                            print(error.localizedDescription)
                        }
                    }
                })
            }
            Section(header: Text("Neues Thema")) {
                TextField("Thema", text: $title)
                Button(action: {
                    withAnimation {
                        if (title != "") {
                            let topic = Topic(context: viewContext)
                            topic.title = title
                            topic.subject = subject
                            do {
                                try viewContext.save()
                                title = ""
                            } catch {
                                print(error.localizedDescription)
                            }
                        }
                    }
                }, label: {
                    Text("Hinzufügen")
                })
            }
        }.navigationTitle(subject.name!)
    }
}

检查 Topic subject 的删除规则:它应该是 Nullify 以防止删除相关对象。在 documentation

中查找更多信息