SwiftUI + Core Data - 更新一个对象(Detail -> DetailEdit)

SwiftUI + Core Data - updating an object (Detail -> DetailEdit)

目标:使用 SwiftUI 更新核心数据对象:DetailView -> EditDetail -> DetailView(已更新)。

问题:下面的代码有效,但创建了一个新对象,而不是更新现有对象。

import SwiftUI

struct DetailView: View {
    
    var order = Order()
    
    @State var showOrderEdit = false


    var body: some View {
        
        Form{
        
        Text(order.tableNumber)
        Text(order.pizzaType)
            
        }
        .navigationTitle(order.pizzaType)
        
        .toolbar {

            ToolbarItem(placement: .primaryAction) {
                
                
                //edit button
                Button(action: {
                    showOrderEdit = true
                }, label: {
                    Text("Edit")
                })
                .sheet(isPresented: $showOrderEdit) {
                    OrderEdit(order: order)
                }
            }
        }

    }
}

import SwiftUI

struct DetailEdit: View {
    
    @State var tableNumber = ""
    
    @Environment(\.managedObjectContext) private var viewContext
    @Environment (\.presentationMode) var presentationMode

    var order = Order()

    var body: some View {
        
        NavigationView {

        
        Form {
        
            TextField("table number", text: $tableNumber)
            
            
            //update button
            Button(action: {
                updateOrder(order: order)
            }) {
                Text("Update")
                    .foregroundColor(.blue)
            }
        
        }
        
        //passing data item detail -> item edit
        .onAppear {
            self.tableNumber = self.order.tableNumber
        }
        
        .navigationTitle("Edit Order")

    }
}
    
    func updateOrder(order: Order) {
        let newtableNumber = tableNumber
        viewContext.performAndWait {
            order.tableNumber = newtableNumber
            try? viewContext.save()
        }
    }
    
  

您在每个视图中创建新的 Order 对象,因此它作为新对象存储到数据库中。相反,您需要从父视图(显示 DetailView)注入 CoreData 对象作为观察对象,

struct DetailView: View {
    
    @ObservedObject var order: Order   // << here !!
    
// .. other code

struct DetailEdit: View {
    
    @State var tableNumber = ""
    
    @Environment(\.managedObjectContext) private var viewContext
    @Environment (\.presentationMode) var presentationMode

    @ObservedObject var order: Order          // << here !!

// ... other code

在这种方法中,您将在两个视图中使用相同的 Order 实例,并且它们将被更新,因为观察该实例以进行修改。