SwiftUI-将fetchResult传递到另一个视图

时间:2020-02-26 14:07:21

标签: core-data swiftui

我正在尝试将FetchResult传递到另一个视图,以便同时更新我的​​所有表。

我的问题:

view1 {
@FetchRequest
ForEach{
NavigationLink(passing fetchRequest.value to View 2)}
}

View2 {
var value1 :fetchRequest.value from view 1
ForEach{
NavigationLink(passing value1.value to View 3)}
}

View3....

这里的问题是,如果我在视图3上进行删除或添加,则视图1和2不会更新,直到我返回视图1,然后再次下降到视图2和3。

您对如何快速更新这些值有想法吗?

最佳

蒂姆

1 个答案:

答案 0 :(得分:0)

我之前从未见过其他人尝试过此操作,但是我只是将@FetchRequest提升为一个超级视图,并将获取结果(在这种情况下为items)作为参数传递给子视图:

struct ContentView: View {
    @State var count = 0
    @FetchRequest<Item>(sortDescriptors: [], predicate: nil, animation: nil) var items
    
    var body: some View {
        NavigationView {
            MasterView(items: items)
                .navigationTitle("Master \(count)")
                .navigationBarItems(trailing: Button("Increment"){
                    count += 1
                })
        }
    }
}


struct MasterView: View {
    var items : FetchedResults<Item>
    
    var body: some View {
        List {
            ForEach(items) { item in
                   Text("Item at \(item.timestamp!, formatter: itemFormatter)")
                }
                .onDelete(perform: deleteItems)
            }
        .toolbar {
//            #if os(iOS)
//            ToolbarItem(placement: .navigation){
//                EditButton()
//            }
//            #endif
            //ToolbarItem(placement: .automatic){
            ToolbarItem(placement: .bottomBar){
                Button(action: addItem) {
                    Label("Add Item", systemImage: "plus")
                }
            }
            ToolbarItem(placement: .bottomBar){
                Button(action: {
                    ascending.toggle()
                }) {
                    Text(ascending ? "Descending" : "Ascending")
                }
            }
        }
    }
    
    
    private func addItem() {
        
        withAnimation {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()
            newItem.name = "Master"
            
            do {
                try newItem.validateForInsert()
                try viewContext.obtainPermanentIDs(for: [newItem])
                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)")
            }
        }
    }

    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            offsets.map {items[$0] }.forEach(viewContext.delete)

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

之所以这样做,是因为我使用了启动参数-com.apple.CoreData.SQLDebug 4,并且我注意到每次状态改变时,它都会命中数据库,并且重新创建了包含@FetchRequest的View,而我没有这样做。不想。