Problem saving data, using CoreData with SwiftUI

你离开我真会死。 提交于 2021-02-05 11:15:29

问题


I just started using CoreData with SwiftUI. After following this series of tutorial. And I am facing a situation where I cannot save data as I expect. Here is the relevant code:

struct MyView: View {
    ......
    @Environment(\.managedObjectContext) var managedObjectContext
    
    func setData() {
        print(#function)
        .....
        let myData = SomeEntity(context: self.managedObjectContext)
        myData.name = "myName"
        myData......
        
        do {
            try self.managedObjectContext.save()
        } catch let error {
            // Handle the Core Data error.
            print("Can't save as expected!!!!")
            print("Error : \(error)")
        }
    }
    
    .....

    var body: some View {
        ........
    }
}

When this code executes I get this error:

Can't save as expected!!!!
Error : nilError

Can somebody tell me what I need to check?

I am all the more puzzled, that I have another part in my app (apparently similar), in a view one level above, where the saving is perfectly working.

In case this may be useful, the view is presented with code like this:

}).sheet(isPresented: $showingFlag) {
    MyView(.....)
}

In the presenting view, data saving is working.


回答1:


Sheets and alerts, etc are modal views. Modal views are normal views, but they are not part of the interface's view hierarchy and are presented on top of the rest of the views on the screen. This means they do not have automatic access to the same @Environment variables that were injected into the interface's view hierarchy (usually in the SceneDelegate or the newer SwiftUI App life-cycle).

To access that same managedObjectContext variable inside the modal View you can pass it along using standard dependency injection.

    }).sheet(isPresented: $showingFlag) {
    MyView(context: managedObjectContext)
}


struct MyView: View {
    ......
    var context: NSManagedObectContext!
    
    func setData() {
        print(#function)


来源:https://stackoverflow.com/questions/63008618/problem-saving-data-using-coredata-with-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!