2 years ago
#72974
K. Shores
Using an @Environment(\.managedObjectContext)—NSManagedObjectContext—in an init function
I have this view.
struct AView: View {
@Environment(\.managedObjectContext) private var viewContext
@State var timestamp: Date
@State private var obj: MyObject
init(date: Date)
{
// this is fine
_timestamp = State(initialValue: date)
// this gives an error
_obj = State(initialValue: MyObject(context: viewContext))
}
var body: some View {
...
}
}
I need to initialize the object obj
, which must be initialized with an NSManagedObjectContext
, inside of the init function. However, when I try to use the code above, I get this error
Variable 'self.obj' used before being initialized
How do I initalize a variable in the init function that depends on an NSManagedObjectContext
?
swift
swiftui
swift5
0 Answers
Your Answer