swift - 为什么一个值变成 nil
问题描述
subject.name
nil
删除时变为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!)
}
}
解决方案
检查您的Topic
删除规则subject
:它应该是 Nullify 以防止删除相关对象。在文档中查找更多信息
推荐阅读
- c# - NotImplementedException in (NetNative)NetworkInterface.GetNetworkInterfaces() Win IoT Core 14393
- python - Pyqt5:单击事件时在 QlineEdit 框中动态传递值
- python - 使用 Django Rest 保存 Base64ImageField 类型将其保存为原始图像。如何将其转换为普通图像
- java - WebSphere MQ 调用失败,compcode '2' ('MQCC_FAILED') 原因 '2397' ('MQRC_JSSE_ERROR'
- filter - 清晰度数据网格自定义过滤器问题:错误类型错误:无法读取 FiltersProvider.add 处未定义的属性“订阅”(
- laravel - Eloquent 连接和求和
- java - 关于java中的单例模式,为什么不直接使用静态变量而不是在方法中将静态变量分配给新的局部变量?
- css - 高度不显示的CSS flexbox
- node.js - 错误:在循环多个请求中发送标头后无法设置标头
- spring - 测试使用 Spring 5 WebClient 的类