Home > Mobile >  SwiftUI: Update Tab Bar Badge when Core Data item is added
SwiftUI: Update Tab Bar Badge when Core Data item is added

Time:05-19

This Problem drives me nuts: I have a small SwiftUi iOS App which works with Core data. All works fine, I can add edit etc. But the app is tab bar based ad I want one tabs badge updated when a record is added to core data.

So I thought I listen to the viewontext.hasChanged bool:

struct MainView: View {
   @Environment(\.managedObjectContext) private var viewContext
   @State var nrOfItems = 0
   let persistanceController : PersistenceController

   var body: some View {
      TabView{
         ItemListView(persistance: PersistenceController.shared)
            .tabItem{
               Label("Lebensmittel",systemImage: "cart")
            }
            .badge(nrOfItems)
      }
      .onChange(of: viewContext.hasChanges, perform: {newValue in
         nrOfItems = persistanceController.getRecordsCount()
      })
   }
}

But the code in onChange is never called ... and I can't find anything about it neither here nor somewhere else. Anyone any hints?

Thanks, Andreas

CodePudding user response:

The hasChanges is not published property, so it does not trigger onChange, try instead to use notification directly, like


.onReceive(NotificationCenter.default.publisher(for: NSManagedObjectContext.didChangeObjectsNotification, 
                                             object: viewContext)) { _ in
  nrOfItems = persistanceController.getRecordsCount()

}

  • Related