【问题标题】:How to update core data info in a SwiftUI view如何在 SwiftUI 视图中更新核心数据信息
【发布时间】:2020-06-24 22:23:25
【问题描述】:

我陷入了僵局。我想显示要编辑的 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 实体更新状态变量,但在 SwiftUI 中似乎没有任何方法可以在不触发有关在更新操作期间修改状态值的警告的情况下执行此操作。我会接受任何解决方案,但似乎应该有一种方法可以实现这一点,而无需使用临时状态变量,只需引用核心数据属性。

【问题讨论】:

    标签: core-data view swiftui


    【解决方案1】:

    这是一条路

    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
    
    

    【讨论】:

    • 我看了很多次,但找不到下划线(在这种情况下)的定义位置。前段时间看到有引用,但是找不到了。
    • @Russ,它是 State 属性包装器的名称。它由编译器自动生成。
    • 感谢您提供此答案,它也对我有用。而且,更新数据的方式真是太糟糕了。不知道开发人员如何自己解决这个问题。
    猜你喜欢
    • 2020-10-29
    • 1970-01-01
    • 2020-06-30
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多