0

I have an environment object that works great but then I added another and when I put this last bit it gives me an error "Cannot use instance member 'brandViewM' within property initializer; property initializers run before 'self' is available" and "Cannot call value of non-function type 'brandViewM, Remove '()''" here

@main
struct testApp: App {

@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@StateObject var listViewModel: ListViewModel = ListViewModel()
@StateObject var brandViewM:brandViewM = brandViewM() //error here

var body: some Scene {
    WindowGroup {
        NavigationView {
            ContentView()
                .onAppear(){
                    UITableView.appearance().backgroundColor = .clear
                }
        }
        .environmentObject(listViewModel)
        .environmentObject(brandViewM)
    }
}
}

Here's that environment object (which is almost exactly like listViewModel)

struct brandItem:Codable, Equatable {
    var selectedText:String
    var brandUsername:String
    var brandPassword:String
}

class brandViewM: ObservableObject {
@Published var branditems: [brandItem] = [] {
    didSet {
        saveBrandItem()
    }
}

let branditemsKey:String = "branditemsKey"

init() {
    getBrandItems()
}

func getBrandItems() {
    guard
        let data = UserDefaults.standard.data(forKey: branditemsKey),
        let savedDotItems = try? JSONDecoder().decode([brandItem].self, from: data)
    else { return }
    
    self.branditems = savedDotItems
}

func deleteBrandItem(indexSet:IndexSet){
    branditems.remove(atOffsets: indexSet)
}

func addBrandItem(selectedText:String, brandUsername: String, brandPassword: String){
    let newBrandItem = brandItem(selectedText: selectedText, brandUsername: brandUsername, brandPassword: brandPassword)
    branditems.append(newBrandItem)
    print(newBrandItem)
}

func saveBrandItem() {
    if let encodedData = try? JSONEncoder().encode(branditems) {
        UserDefaults.standard.set(encodedData, forKey: branditemsKey)
    }
}
}

And have @EnvironmentObject var brandVM: brandViewM in a view where im displaying the Strings in a ForEach. The only difference between this environment object and the first one I made is that the ForEach required brandItem to conform to Hashable, and the in first one instead its Equatable. Any help would be appreciated.

  • Can you show code for the view that contains `NavigationView { .. }.environmentObject(brandViewM)`? – aheze Sep 24 '21 at 02:29

1 Answers1

0

This is what happens when you use bad naming for your classes. You are using:

.environmentObject(brandViewM) //error here

and brandViewM is a type (and this is what the error tells you), not an instance. You should use the normal convention of starting your type using uppercase, and your instances lowercase. Now you know how to fix this. If you want to keep your bad naming, use this:

.environmentObject(brandViewM()) //<--- here