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


10

我正在尝试通过构建一个作业管理应用程序来自学核心数据。我的代码构建良好,并且该应用程序可以正常运行,直到我尝试向列表中添加新任务。我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()
    }
}

您在哪里将托管对象上下文添加到环境?该管理对象上下文是如何创建的?看来您尚未将其与持久性商店协调员联系在一起
Paulw11,19年

我在原始帖子中为您添加了将Moc添加到环境中的代码。
凯文·奥尔马茨

@KevinOlmats我的答案有帮助吗?
fulvio

检查您是否已通过环境分配了上下文.environment(\.managedObjectContext, viewContext)
onmyway133

@ onmyway133,这是正确的答案
Kevin Olmats,

Answers:


8

您实际上并没有保存上下文。您应该执行以下操作:

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

do {
    try self.moc.save()
} catch {
    print(error)
}

另外,您@FetchRequest(...)可能看起来像这样:

@FetchRequest(fetchRequest: CourseItem.getCourseItems()) var courses: FetchedResults<CourseItem>

您可以修改您的CourseItem类以处理sortDescriptors以下内容:

public class CourseItem: NSManagedObject, Identifiable {
    @NSManaged public var name: String?
    @NSManaged public var dueDate: Date?
    // ...etc
}

extension CourseItem {
    static func getCourseItems() -> NSFetchRequest<CourseItem> {
        let request: NSFetchRequest<CourseItem> = CourseItem.fetchRequest() as! NSFetchRequest<CourseItem>

        let sortDescriptor = NSSortDescriptor(key: "dueDate", ascending: true)

        request.sortDescriptors = [sortDescriptor]

        return request
    }
}

然后,您将ForEach(...)像下面这样进行修改,并且还可以很容易地处理项目的删除:

ForEach(self.courses) { course in
    // ...
}.onDelete { indexSet in
    let deleteItem = self.courses[indexSet.first!]
    self.moc.delete(deleteItem)

    do {
        try self.moc.save()
    } catch {
        print(error)
    }
}

您要确保的一件事是将“类名”设置为“ CourseItem”,CourseItem该类与我们之前创建的类匹配。

只需单击文件中的ENTITIES.xcdatamodeId然后将所有内容都设置为以下内容(包括将Module设置为“ Current Product Module”,将Codegen设置为“ Manual / None”):

在此处输入图片说明

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.