12

Is it possible to use a @EnvironmentObject inside an ObservableObject?

It is giving me an error:

Fatal error: No ObservableObject of type EntryViewModel found. A View.environmentObject(_:) for EntryViewModel may be missing as an ancestor of this view.: file SwiftUI, line 0

I know the @EnvironmentObject is good because I use it other places.

If not, how can I get the information?

class ResultsViewModel: ObservableObject {
    @EnvironmentObject var entry: EntryViewModel
    ...
}

Thank you.

2 Answers 2

7

Is it possible to use a @EnvironmentObject inside an ObservableObject?

No, it is not. @EnvironmentObject can be used in View only.

If not, how can I get the information?

A possible solution is to pass it in init:

class ResultsViewModel: ObservableObject {
    var entry: EntryViewModel

    init(entry: EntryViewModel) {
        self.entry = entry
    }
}

Another solution may be to use a singleton or (maybe the best) dependency injection.

Sign up to request clarification or add additional context in comments.

8 Comments

I tried the init() and it was a no go. caused other issues. thanks.
@diogenes EnvironmentObject is kind of a singleton for views. If you want to have it always available you may need to use a singleton or dependency injection
this is sort of over my pay grade. researching now... thanks.
Interestingly you can use Environment in ObservableObject. Even though documentation describes Environment as "a property wrapper that reads a value from a view’s environment".
@SerhiiK Is that so? Please confirm :) Am running to go test.
|
6

You could go via DynamicProperty making use of its update func, e.g.

class MyObject: ObservableObject {
    var context: NSManagedObjectContext? 
}

struct MyProperty: DynamicProperty {
    @Environment(\.managedObjectContext) private var viewContext
    @StateObject var object = MyObject()

    // update is called before body in the View containing this property
    func update() {
        // environment vars now are valid

        if object.context != viewContext {
            // do something
            object.context = viewContext
        }
    }
}

struct MyView {
    var myProperty = MyProperty()

    var body: some View {
    }
}

1 Comment

Any downside to this approach? I don't see it recommended much but it looks great

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.