UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: What is the appropriate way of passing an NSManagedObjectContext instance from ContextView through to Subviews specially ones presented as modals?

Forums > 100 Days of SwiftUI

Hi,

I am absolutely lost trying to figure out how to pass the instance of NSManagedObjectContext from ContentView through to subviews specially ones being presented as a modal. From what I understand this is a bug/limitatin of SwiftUI/iOS13 at the moment.

ContentView calls the modal as follows:

.sheet(isPresented: $showLicenseManager) {
     () -> LicenseManagerView in
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    return LicenseManagerView().environment(\.managedObjectContext, context) as! LicenseManagerView
 }

and I am using accessing the NSManagedObjectContext instances as:

@Environment(\.managedObjectContext) var managedObjectContext

when I attempt to access the results of a FetchRequest defined as:

@FetchRequest(entity: License.entity(), sortDescriptors: [
    NSSortDescriptor(keyPath: \License.timestamp, ascending: false)
]) var licenses: FetchedResults<License>

in a list (note: the instance of Text is left there for testing purposes):

NavigationView {
    List {
        ForEach(licenses, id: \.name) { license in
            Text("Test")
        }
    }

I am met with the following error:

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x600001964be0 UIView:0x7fcd0a420380.width == - 16   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
Could not cast value of type 'SwiftUI.ModifiedContent<DemoApp.LicenseManagerView, SwiftUI._EnvironmentKeyWritingModifier<__C.NSManagedObjectContext>>' (0x7fcd0b09bf10) to 'NSManagedObjectContext' (0x7fff89c1c660).
2020-04-15 21:56:40.101515+1000 DemoApp[60019:3989730] Could not cast value of type 'SwiftUI.ModifiedContent<DemoApp.LicenseManagerView, SwiftUI._EnvironmentKeyWritingModifier<__C.NSManagedObjectContext>>' (0x7fcd0b09bf10) to 'NSManagedObjectContext' (0x7fff89c1c660)

Note: that I can perfectly well access the NSManagedObjectContext instance in the ContextView and have managed to build a list of entities from the above query and managed to add objects to the database.

Questions:

  • What are ways in which we can pass the instance of NSManagedObjectContext from the ContentView to subviews, specially ones presented as modals
  • Is the above approach in the right direction or have I missed the mark completely?

Any points will be much appreciaed. I seem to be going around in circles at the moment. Thank you for your time.

3      

Hey there I was yesterday struggling with the same thing.. And what I found working is that you need to add in ContentView

@Environment(\.managedObjectContext) var moc

Then you need to pass it to a SheetView:

.sheet(isPresented: $showingSheet) {
    AddClientView().environment(\.managedObjectContext, self.moc)
}

Then in AddClientView I'm creating again environment variable of managedObjectContext

@Environment(\.managedObjectContext) var moc

And that's all I could make FetchRequests or in my case add Client data to CoreData.

P.s. This all is working with the default CoreData implementation.

4      

Thanks so much @Sangsom I didn't realise that

.sheet(isPresented: $showLicenseManager) { 
    LicenseManagerView().environment(\.managedObjectContext, self.managedObjectContext)
}

was a valid call. Much appreicate you taking time to respond.

4      

@twostraws  Site AdminHWS+

FWIW, Apple considers this a bug, so it looks like modals might inherit environment from their parent in a future release.

4      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.