NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

SOLVED: Update view when CoreData fetched item property is changed

Forums > SwiftUI


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: \, 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))

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



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

hope that helps,




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


Hacking with Swift is sponsored by RevenueCat

SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.

Try it for free

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

Reply to this topic…

You need to create an account or log in to reply.

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.