首页 > 解决方案 > 当 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 数组来填充视图。但我到目前为止无法实现这一点。

在此处输入图像描述

标签: swiftcore-dataswiftui

解决方案


所有 CoreData 对象都是ObservableObjects,因此需要将它们包装起来,@ObservedObject以便在View发生更改时可以刷新

@ObservedObject var selectedNode : Node

此外,请确保您正在使用@FetchRequestNSFetchedRequestController可以观察到商店的变化。NSFetchRequest不观察商店。


推荐阅读