0

I have a class method that apparently doesn't see the @EnvironmentObject var categories: Categories object at the top of the class. I know that this works since I use it in several other files. It also means that my coding in SceneDelegate is correct. The software is crashing with the error: Thread 1: Fatal error: No ObservableObject of type Categories found. A View.environmentObject(_:) for Categories may be missing as an ancestor of this view. The error is occurring in the method updateTotals() in the "for" loop

struct CatItem:  Codable, Identifiable {
    var id = UUID()
    var catNum: Int
    var catName: String  <-- this is the class I'm trying to reference
    var catTotal: Double   
    var catPix: String   
    var catShow: Bool
}

    class Categories: ObservableObject {
        
        @Published var catItem: [CatItem] 
           
        }




class BaseCurrency: ObservableObject {
    
    @EnvironmentObject var userData: UserData
    @EnvironmentObject var categories: Categories
    
    var foundNew: Bool = false 
    var newRate: Double = 0.0
    
    var baseCur: BaseModel
    
    
    //-----------------------------------------------------
    // new base currency so need to update the system totals
    //-----------------------------------------------------
    func updateTotals() -> () {
        
        for index in 0...(categories.catItem.count - 1) {      <-- error here
            categories.catItem[index].catTotal *= self.newRate
        }
        
        userData.totalArray[grandTotal] *= self.newRate
        userData.totalArray[transTotal] *= self.newRate
        userData.totalArray[userTotal] *= self.newRate
        
        let encoder = JSONEncoder()
        if let encoded = try? encoder.encode(self.baseCur) {
            UserDefaults.standard.set(encoded, forKey: "base")
        }
   
        self.foundNew = false
    }
}
Galen Smith
  • 299
  • 2
  • 14

1 Answers1

0

I was reading somewhere recently that @EnvironmentObject is just like @State in that a change in either parameter will cause body to update the view. Therefore neither of these should be in a class. I have reorganized my software and have not seen the error since.

Galen Smith
  • 299
  • 2
  • 14