我有一个类方法,显然在类的顶部看不到 @EnvironmentObject var categories: Categories 对象。我知道这很有效,因为我在其他几个文件中使用了它。这也意味着我在 SceneDelegate 中的编码是正确的。软件因错误而崩溃:线程 1:致命错误:未找到类别类型的 ObservableObject。类别的 View.environmentObject(_:) 作为此视图的祖先可能会丢失。错误发生在“for”循环中的方法 updateTotals() 中
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
}
}