使用CoreData和SwiftUI保存数据时出现问题 [英] Problem saving data, using CoreData with SwiftUI

查看:55
本文介绍了使用CoreData和SwiftUI保存数据时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始将 CoreData SwiftUI 一起使用.在遵循本系列教程.而且我正面临无法按预期保存数据的情况.这是相关代码:

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.

推荐答案

表格和警报等是模式视图.模态视图是普通视图,但它们不是界面视图层次结构的一部分,并显示在屏幕上其余视图的顶部.这意味着他们无法自动访问注入到界面视图层次结构中的同一 @Environment 变量(通常在SceneDelegate或更新的SwiftUI App生命周期中).

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).

要在模式视图中访问相同的ManagedObjectContext变量,可以使用标准依赖项注入将其传递.

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)

这篇关于使用CoreData和SwiftUI保存数据时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆