0

I'm using a core data child context to separate temporary entities from my main context, but when I pass in the main context as an environment variable, I don't have access to it in order to initialize the child context and get a 'self' used before all stored properties are initialized error

Any suggestions?

struct CreatePlayerView: View {
    @State private var newPlayer: PlayerEntity
    @Environment(\.managedObjectContext) private var managedObjectContext

    private let childManagedObjectContext: NSManagedObjectContext

    init() {
        childManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)

        \\ 'self' used before all stored properties are initialized
        childManagedObjectContext.parent = managedObjectContext

        newPlayer = PlayerEntity(context: childManagedObjectContext)
    }

    var body: some View {
        EditPlayerViewDetail(
            player: $newPlayer,
            onDone: { player in
                try? childManagedObjectContext.save()
            }
        )
    }
}
Shawn
  • 416
  • 5
  • 18
  • 2
    You won't have access to the `Environment` yet in the initializer -- probably best to explicitly pass it into the initializer if you need it, or wait until `onAppear` to do your loading. – jnpdx Oct 18 '21 at 23:00
  • 1
    Does this answer your question https://stackoverflow.com/a/63224046/12299030? – Asperi Oct 19 '21 at 04:48
  • Yes, nice! Go ahead and answer it and I'll accept. – Shawn Oct 19 '21 at 13:41

0 Answers0