当前位置: 首页 > 面试题库 >

CoreData和SwiftUI:环境中的上下文未连接到持久性存储协调器

鲜于德业
2023-03-14
问题内容

我正在尝试通过构建一个作业管理应用程序来自学核心数据。我的代码构建良好,并且该应用程序可以正常运行,直到我尝试向列表中添加新任务。我Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1c25719e8)在以下行中收到此错误:ForEach(courses, id: \.self) { course in。控制台也有此错误:Context in environment is not connected to a persistent store coordinator: <NSManagedObjectContext: 0x2823cb3a0>

我对Core
Data知之甚少,对可能的问题不知所措。我已经在数据模型中设置了“分配”和“课程”实体,其中Course与“分配”具有一对多关系。每个作业将根据特定课程进行分类

这是用于向列表添加新分配的视图的代码:

    struct NewAssignmentView: View {

    @Environment(\.presentationMode) var presentationMode
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Course.entity(), sortDescriptors: []) var courses: FetchedResults<Course>

    @State var name = ""
    @State var hasDueDate = false
    @State var dueDate = Date()
    @State var course = Course()

    var body: some View {
        NavigationView {
            Form {
                TextField("Assignment Name", text: $name)
                Section {
                    Picker("Course", selection: $course) {
                        ForEach(courses, id: \.self) { course in
                            Text("\(course.name ?? "")").foregroundColor(course.color)
                        }
                    }
                }
                Section {
                    Toggle(isOn: $hasDueDate.animation()) {
                        Text("Due Date")
                    }
                    if hasDueDate {
                        DatePicker(selection: $dueDate, displayedComponents: .date, label: { Text("Set Date:") })
                    }
                }
            }
            .navigationBarTitle("New Assignment", displayMode: .inline)
            .navigationBarItems(leading: Button(action: {
                self.presentationMode.wrappedValue.dismiss()
            }, label: { Text("Cancel") }),
                                trailing: Button(action: {
                                    let newAssignment = Assignment(context: self.moc)
                                    newAssignment.name = self.name
                                    newAssignment.hasDueDate = self.hasDueDate
                                    newAssignment.dueDate = self.dueDate
                                    newAssignment.statusString = Status.incomplete.rawValue
                                    newAssignment.course = self.course
                                    self.presentationMode.wrappedValue.dismiss()
                                }, label: { Text("Add").bold() }))
        }
    }
}

编辑:这是AppDelegate中设置持久性容器的代码:

lazy var persistentContainer: NSPersistentCloudKitContainer = {
    let container = NSPersistentCloudKitContainer(name: "test")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

还有SceneDelegate中设置环境的代码:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

    // Get the managed object context from the shared persistent container.
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    // Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath.
    // Add `@Environment(\.managedObjectContext)` in the views that will need the context.
    let contentView = ContentView().environment(\.managedObjectContext, context)

    // Use a UIHostingController as window root view controller.
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView)
        self.window = window
        window.makeKeyAndVisible()
    }
}

问题答案:

像moc这样的环境值仅自动传递到层次结构中的其他视图。因此,如果您显示工作表或不属于视图层次结构的任何内容,则将失去环境,并且需要像向ContentView一样将moc传递给新层次结构。检查以下代码段:

.sheet(isPresented: self.$showSheet) {
            SheetView()
                .environment(\.managedObjectContext, self.moc)
        }


 类似资料:
  • 如果一次调用<code>会话。保存(customerObject)则不需要插入客户…查询数据库。Hibernate将设置id属性(“序列”或“增量”生成器),并将实体绑定到持久性上下文。当<code>事务时,持久性上下文与数据库同步。调用commit() Q:Hibernate将在哪里设置id属性 Q:在与db同步之前,持久性上下文缓存sql查询是否会插入到customer…中?我的意思是,何时生

  • 问题内容: 我是Java世界和JPA的新手。我在学习JPA时遇到了许多新术语,例如Entity,persistence。在阅读时,我无法理解 Persistence Context 的确切定义。 谁能用简单的外行术语解释它?与中使用的数据有什么关系? 例如,我发现此定义太复杂而难以理解: 持久性上下文是一组实体,因此对于任何持久性标识,都有一个唯一的实体实例。 问题答案: 持久性上下文处理一组实体

  • 持久性上下文是一组实体,因此对于任何持久性标识都有一个唯一的实体实例。

  • 我正在将堆栈转换为K8S。数据库需要持久存储。 我使用了 pv.yaml(根据@Whites11的回答进行了编辑): 我进入GUI上的PVC页面,并手动向索赔添加了一个卷(基于@Whites11的反馈)。我可以看到PVC已经更新了体积,但它仍然悬而未决。 意识到自从进行@Whites11建议的更改后,pod中的原始错误消息已经更改。现在是“persistentvolume”pvvolume“not

  • 问题内容: 事务范围的持久性上下文和扩展的持久性上下文之间有什么区别? 问题答案: 在JSR-220 Enterprise JavaBeans 3.0规范中清楚地解释了差异: 5.6容器管理的持久性上下文 (…) 可以将容器管理的持久性上下文定义为具有范围为单个事务的生存期或跨越多个事务的扩展生存期,这取决于创建容器时所指定的生存期 。该规范分别将这种持久性上下文称为 事务范围的持久性上下文 和

  • 我有一个应用程序,为外部存储上的备份文件创建目录,并在用户退出应用程序时自动创建备份文件。每周创建一个备份文件,然后用最新信息覆盖一个备份文件。 无法在中找到备份文件,因为它们需要在用户重新安装应用程序后继续存在 我不能使用,因为它不是图像或视频 我无法使用在用户每次退出应用程序时要求他保存备份文件 那个么,如何使用新的作用域存储自动创建持久备份文件呢? (如果用户想要恢复其中一个备份文件,我还需