swiftuiswiftui-state

How to avoid SwiftUI Initial View getting initialized multiple times when @State variables are initialized?


struct GroceryList: View {
  @ObservedObject var coreDataViewModel:CoreDataViewModel = CoreDataViewModel() 
  @StateObject var userPreferences: UserPreferences = UserPreferences()
  @State private var selectedItemsInList: [GroceryItem] = []
  @State private var selection = Set<UUID>()//for check box
  @State private var activeTab:Int = 0 //for active tab

The above View gets initialized 3 times as and when the @State variables selection and activeTab gets initialized. I have a init() in GroceryList: View like given below:

 init() 
{
   print("Grocery List View")
}

Grocery List View gets printed thrice.

Since I instantiate and initialize a CoreData View Model firstly, its fetchItems() in CoreDataViewModel init is also done thrice.

How to avoid initialization happening multiple times?

This is my first SwiftUI app in the development phase with self-learning.Any pointers greatly appreciated.


Solution

  • CoreDataViewModel initializes 3 times most certainly because you have @ObservedObject, where you have to have @StateObject. Or you can inject this view model as a parameter, leaving @ObservedObject. Or you can use @EnvironmentObject in conjunction with .environmentObject() view modifier.

    Also, if by "view initializes" 3 times, you mean its onAppear gets called multiple times - this means your view does not have stable identity. Check Demystifying SwiftUI talk to learn more, but briefly, you need to ensure that view has a stable structural identity, and/or explicit .id() identity.