0

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?

K. Shores
  • 875
  • 1
  • 18
  • 46
  • 2
    Does this answer your question https://stackoverflow.com/a/63224046/12299030? – Asperi Jan 20 '22 at 05:46
  • If `MyObject` is a Core Data entity, you shouldn't be using it with `@State` in the first place. That property wrapper doesn't work so well with reference types, which `NSManagedObject`, being a class, is. – Patrick Wynne Jan 20 '22 at 08:11
  • Ya, I ended up taking in the object not as a state variable. @PatrickWynne is correct in this – K. Shores Jan 20 '22 at 14:20

0 Answers0