UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: An extra row is created on each update of coredata

Forums > SwiftUI

I have a simple form with one filed of a specific type that i am getting , every thing is perfect so far I am also able to update the record when i press enter/return. However when i go back and see the list i find an extra row has been created along with correct update what can be the reason of this , can any one suggest , like an extra managedObjectContext , wrong initialisation or any thing else

the code is as below

import SwiftUI
import CoreData

struct EditViewData: View {

    @Environment(\.managedObjectContext) var moc
    @Binding var carData: CarDetails
    @ObservedObject var dataEdit: DataController

    var body: some View {
        VStack {
            TextField("Brand", text: .init(
                get: { self.carData.brandNameTemp  },
                set: { self.carData.brandName = $0 }
            )) {
                let carChange = CarDetails(context: moc)        <----- context
                if carChange.carid == carData.carid {
                    carChange.brandName = carData.brandName
                }   <-----edit
                dataEdit.save()   <-----save
            }

        }
        .navigationBarBackButtonHidden(true)

    }
}

1      

hi Amit,

if the point of your EditViewData is to simply edit one field of an existing Core Data object (of type CarDetails), there is no reason to be executing this statement:

let carChange = CarDetails(context: moc)

this creates a new Core Data object in the managedObjectContext, and so it is no surprise that you find a new item has been added when you return to a list of such objects. (or are you trying to make this view perform both functions of "edit an existing carData" and "add a new carData?)

there may be more to discuss about your code, so let's see where you go next.

hope this helps,

DMG

2      

I made one more change , thanks DMG , its all fine now

@Binding var carData: CarDetails

to

@ObservedObject var carData: CarDetails

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.