swift - 当 CoreData 更改时更新 SWitfui 视图
问题描述
我正在处理一个有关系的 coredata 实体。问题是,然后我将一个项目附加到 UI 未更新的子数组。
var selectedNode : Node
var body: some View {
VStack {
ForEach(selectedNode.childrenArray) { item in
NavigationLink {
Text("Item at \(item.text!)")
} label: {
Text(item.text!)
}
}
}
.toolbar {
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
}
private func addItem() {
withAnimation {
viewContext.performAndWait {
let newItem = Node(context: viewContext)
newItem.text = "Hello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello world"
newItem.dateAdded = Date()
selectedNode.addToChildren(newItem)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
正如预期的那样,当您使用 coredata 数组填充视图时,它会使用 coredata 中的任何更改自动更新视图。但是由于我们没有直接使用 coredata 数组来填充视图,我应该如何更新View
.
想到的一种可能的解决方案是使用谓词来获取属于“子数组”的项目,这样我们就可以直接使用 coredata 数组来填充视图。但我到目前为止无法实现这一点。
解决方案
所有 CoreData 对象都是ObservableObject
s,因此需要将它们包装起来,@ObservedObject
以便在View
发生更改时可以刷新
@ObservedObject var selectedNode : Node
此外,请确保您正在使用@FetchRequest
或NSFetchedRequestController
可以观察到商店的变化。NSFetchRequest
不观察商店。
推荐阅读
- linux - Bash 脚本 SSH 命令变量插值
- python - 如何在 docker run 期间将来自 k8s 的 ENV 变量提供给 python 应用程序
- webrtc - 如何防止 JsSIP 要求麦克风访问?
- java - 无法在 Spring REST API 中将 swagger2 版本从 2.7.0 升级到 3.00(常规 Spring 不是 sprint 启动)
- apache-kafka - 发生错误时如何关闭KafkaListener
- angular - 第一次从事 Angular 项目,我想知道如何根据点击从 url 中提取 id
- c# - MongoDB 和 C# - 大型文档检索
- javascript - 如何缩小图像以填充屏幕尺寸?
- swift - ForceTouch:控制反馈的幅度
- python - 如何从 Pandas 数据框列中制作一对项目