gpt4 book ai didi

swift - CoreData 和 SwiftUI : Context in environment is not connected to a persistent store coordinator

转载 作者:行者123 更新时间:2023-12-02 04:11:50 29 4
gpt4 key购买 nike

我正在尝试通过构建一个作业管理应用程序来自学核心数据。我的代码构建良好,应用程序运行正常,直到我尝试将新分配添加到列表中。我收到此错误 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> .

我对核心数据知之甚少,并且不知道问题可能是什么。我在数据模型中设置了“作业”和“类(class)”实体,其中类(class)与作业具有一对多关系。每项作业都将分类在特定类(class)下。

这是向列表添加新分配的 View 的代码:

    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 这样的环境值只会自动传递到层次结构中的其他 View 。因此,如果您显示工作表或任何不属于 View 层次结构的内容,您将丢失环境,并且需要将 moc 传递到新层次结构,就像您对 ContentView 所做的那样。检查此代码片段:

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

关于swift - CoreData 和 SwiftUI : Context in environment is not connected to a persistent store coordinator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59166513/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com