【发布时间】:2021-11-08 16:34:14
【问题描述】:
我正在处理具有关系的 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 对象包装在
@ObservedObject中,并确保您使用的是@FetchRequest或NSFetchedResultsController。其他 fetch 请求,例如NSFetchRequest没有观察存储。@ObservedObject var selectedNode : Node -
nodes[0],这是什么?在您的代码示例中,我没有看到任何nodes的定义。 -
@JoakimDanielson 现在更正了代码。
-
@loremipsum 嗯,这很简单。
@ObservedObject var selectedNode : Node已修复!