How to leverage coreData and .ontapGesture on Observable Macro
00:16 10 Feb 2025
@Observable class CoreDataInterViewModel {
    let container: NSPersistentContainer
    var savedEntities: [Fish] = []

init() {
    container = NSPersistentContainer(name: "Fish")
    container.loadPersistentStores { (description, error) in
        if let error = error {
            print("ERROR LOADING CORE DATA. \(error)")
        } else {
            print("SUCCESSFULLY LOADED CORE DATA. \(description)")
        }
    }
    fetchFish()
}

// MARK: - FUNCTION

 func fetchFish() {
    
    let request = NSFetchRequest(entityName: "Fish")
    do {
        savedEntities = try container.viewContext.fetch(request)
    } catch  {
        print("ERROR FETCHING CORE DATA: \(error)")
    }
}

 func saveData() {
    do {
        try container.viewContext.save()
        fetchFish()
        
    } catch {
        print("Error SAVING: \(error)")
    }
}

View model code:

struct CoreDataInterr: View {

// property
var vm: CoreDataInterViewModel = .init()
@State var textFieldText: String = ""

var body: some View { ...

List {
                ForEach(vm.savedEntities) { fish in
                    Text(fish.name ?? "NoNAME")
                        .onTapGesture {
                            vm.updateFish(fish: fish)
                        }
                } //: LOOP
                .onDelete(perform: vm.deleteFish)
            } //: LIST
            .listStyle(.plain)}

What I'm trying to apply is tap the entities I received as list in view, and the updateFish method works. Of course, I found a problem that print works properly, but it doesn't update in the view.

Once I run .onTapGesture, '~' is created after the selected fish, but it doesn't work when I click it multiple times, and only when I did another action, I could see that ~~~~ is created as many times as I tap.

 var savedEntities: [Fish] = [] 

It is not detected by view and not updated because Fish is the reference type as NSMangedObject and changes the attribute name?

But it's really weird that '~' is created once it's run.

Could you help me?

swiftui entity