CoreData always takes the same item

I have the problem that when I want to edit the item, the item that was created last is always changed.



//  EditSheet.swift

//  CoreData_T

//

//  Created by Janik Hartmann on 11.01.23.

//



import SwiftUI

import Foundation

import CoreData



struct EditSheet: View {

    @Environment(\.managedObjectContext) private var viewContext

    @Environment(\.dismiss) private var dismiss

    

    @State private var name: String = ""

    private var item: Item

    var itemid: UUID

   

    

    init(itemId: UUID, item: Item) {

                self.item = item

                self.itemid = item.id!

                self.name = item.name ?? ""

            }

        



    var body: some View {

        VStack{

            TextField("Text eingeben", text: $name)

                .padding()

            Button {

                

                update(item: item, itemid: item.id!)

                dismiss()

                

                

            } label: {

                Text("Save")

            }.padding()

        }.onAppear{

            name = item.name!

            

        }

    }

    func update(item:Item, itemid id: UUID){

        let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Item")

        fetchRequest.predicate = NSPredicate(format: "id = %@", itemid as CVarArg)

        

        do {

            let results = try viewContext.fetch(fetchRequest) // Rufe den Fetchrequest auf

            let objectToUpdate = results[0] // Nehme das erste

            objectToUpdate.setValue(name, forKey: "name") //Editiere den Key "name" zum übergebenen Wert



            do {

                try viewContext.save() // Speichern

                print("Erfolgreich gespeichert!")

            } catch let error as NSError {

                print("Fehler beim Speichern. \(error), \(error.userInfo)")

            }

        } catch let error as NSError {

            print("Fehler beim Fetchen. \(error), \(error.userInfo)")

        }

    }

}


Answered by Claude31 in 742097022

A possible reason is that by invoking the state var showeditsheet,

         HStack {
                Text(item.name + "\(showeditsheet ? "" : "") "?? "Not found")

it forces some reevaluation of views (such as the sheet to present or even the whole List view).

                        .sheet(isPresented: $showeditsheet){
                            EditSheet(itemId: item.id!, item:item)

So, don't forget to close this long thread on this answer. And good continuation.

I pasted this line of code from you and instead of "T" : "F" I left the string empty with "" : "". And now it works. I don't know exactly why, but it works. Thank you very much for your help. You have helped me a lot!

Accepted Answer

A possible reason is that by invoking the state var showeditsheet,

         HStack {
                Text(item.name + "\(showeditsheet ? "" : "") "?? "Not found")

it forces some reevaluation of views (such as the sheet to present or even the whole List view).

                        .sheet(isPresented: $showeditsheet){
                            EditSheet(itemId: item.id!, item:item)

So, don't forget to close this long thread on this answer. And good continuation.

CoreData always takes the same item
 
 
Q