How to detect changes to a property of a core data object

Viewed 254

I have this core data entity called Cake, that has properties like:

  • numberOfIngredientsBeingUsed
  • numberOfIngredientsTotal
  • color
  • weight

I read one object from the entity and now I have something like this

let orangeCake = Cake(type:"orange", context:coreDataContext)

Now I want to show a ProgressView. I want to pass the progress view, a binding numberOfIngredientsBeingUsed property, representing the current number of ingredients so far being used and a regular property numberOfIngredientsTotal, representing the total number of ingredients required to make the cake.

The idea is that when numberOfIngredientsBeingUsed changes on the main view, the progress view updates, because it is a binding property.

How do I do that? I cannot wrap my brain around, because numberOfIngredientsBeingUsed is a property of the cake object orangeCake.

1 Answers

CoreData managed objects are type of ObservableObject, so instead of passing one property you need to inject entire instance of Cake as ObservedObject and use its properties inside ProgressView, which will update (and refresh view) whenever corresponding object updated somewhere in other part of code.

So it should look like

struct ProgressView: View {
   @ObservedObject var model: Cake

   var body: some View {
      Text("Progress: \(model.numberOfIngredientsBeingUsed) of \(model.numberOfIngredientsTotal)")
   }
}
Related