Russ
Russ

Reputation: 576

How to update core data info in a SwiftUI view

I have reached an impasse. I would like to display data from CoreData to be edited and then update it back into the database. There doesn't seem to be any way to do this but it is such a basic operation I'm sure the problem is on my end.

Here's the code I have

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

I've tried a number of ways to update the State variables from the CoreData Customer entity but there doesn't seem to be any way in SwiftUI to do this without triggering warnings about modifying the state values during an update operation. I'll accept any solution but it seems like there should be a means of accomplishing this without needing to use temporary state variables, just references to the core data attributes.

Upvotes: 1

Views: 665

Answers (1)

Asperi
Asperi

Reputation: 258345

Here is a way to go

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

Upvotes: 2

Related Questions