如何在SwiftUI视图中更新核心数据信息

时间:2020-06-24 22:23:25

标签: core-data view swiftui

我陷入僵局。我想显示来自CoreData的数据进行编辑,然后再将其更新回数据库。似乎没有任何方法可以执行此操作,但这是一个基本操作,我确信问题就在我身上。

这是我的代码

import SwiftUI
import CoreData

struct CustomerEditView: View
{
    @Environment(\.managedObjectContext) var context
    
    @State var firstName = ""
    @State var lastName = ""
    @State var phone = ""
    @State var email = ""
    @State var birthday = ""
    
    var customer: Customer
    
    var body: some View
    {
        //firstName = customer.firstName!
        //lastName = customer.lastName!
        //phone = customer.phone!
        //email = customer.email!
        
        return VStack
        {
        TextField("First Name", text: $firstName)
        TextField("Last Name", text: $lastName)
        TextField("Cell Phone", text: $phone)
        TextField("EMail", text: $email)
        TextField("Birthday", text: $birthday)
        Button("Save")
        {
            do
                    {
                        //customer.birthday = self.birthday
                        customer.firstName = firstName
                        customer.lastName = lastName
                        customer.phone = phone
                        customer.email = email
                        try context.save()
                    }
            catch
            {
                print(error.localizedDescription)
            }
            
        }
        }
    }
}

我尝试了多种方法来从CoreData Customer实体更新State变量,但是SwiftUI中似乎没有任何方法可以在更新操作期间不触发有关修改状态值的警告。我会接受任何解决方案,但似乎应该有一种无需使用临时状态变量即可完成此操作的方法,只需引用核心数据属性即可。

1 个答案:

答案 0 :(得分:0)

这是一条路

struct CustomerEditView: View
{
    @Environment(\.managedObjectContext) var context
    
    @State var firstName: String    // << declare only

    // ... other states are the same
    
    var customer: Customer

    init(customer: Customer) {
        self.customer = customer

        // create state with initial value from customer
        _firstName = State(initialValue: customer.firstName ?? "")   // << here !!
        
        // ... other states are the same
    }
    
    var body: some View
    {
        // .. other your code