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

SOLVED: Update view when CoreData fetched item property is changed

Forums > SwiftUI

@Cryv  

Hello I need some more help.

I have a CoreData model named Item, which in turn has some properties like name, price, quantity

The items are store in an array placed in the model of the app

struct PosViewModel {
    let persistenceController = PersistenceController.shared
    let container: NSPersistentContainer
    let viewContext: NSManagedObjectContext

    var ticket: [Item] = []

    init() {
        container = persistenceController.container
        viewContext = container.viewContext

        let request = NSFetchRequest<Category>(entityName: "Category")
        request.sortDescriptors = [NSSortDescriptor(keyPath: \Category.name, ascending: true)]

        do {
            categories = try viewContext.fetch(request)
          } catch let error as NSError {
            print("Could not fetch. \(error), \(error.userInfo)")
          }
    }
}

When i change the property of the item like

ticket[index].quantity += 1

The view does not update

For now I'm using a very ugly workaround like this:

ticket.append(Item(context: viewContext))
ticket.popLast()

With this in place the view updates cause I add and remove an element from the array

Of course PosViewModel is declared as @Published in my ViewModel class, the other stuff works and the views update normally but not when i change a property inside the coredata item.

Thank you

2      

hi,

Item is an object (a class), so changing one of its properties/Core Data attributes does not register as a change to the ticket array ... the object references in the array remain the same. and that's why your ugly workaround is required.

put a method in your ViewModel such as this to make a quantity increment and have it publish the change:

func incrementQuantity(for item: Item) {
  item.quantity += 1
  objectWillChange.send()
}

hope that helps,

DMG

4      

@Cryv  

Oh my god it was this easy. This worked gread thank you very much!

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.