首页 > 解决方案 > 为什么一个值变成 nil

问题描述

subject.namenil删除时变为topic.

我怎么解决这个问题?

塔安克斯。

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!)
    }
}

标签: swiftcore-dataswiftui

解决方案


检查您的Topic删除规则subject:它应该是 Nullify 以防止删除相关对象。在文档中查找更多信息

在此处输入图像描述


推荐阅读