我正在尝试制作一个编辑表单,该表单可以将值作为 @Binding 进行编辑,然后提交更改。在这种情况下,我使用 @FetchRequest 属性包装器填充包含核心数据记录的列表。我想点击一行从列表导航到详细信息视图,然后在详细信息视图上导航到编辑视图。

我尝试在没有 @Binding 的情况下执行此操作,代码将编译,但是当我进行编辑时,它不会反映在之前的屏幕上。似乎我需要使用@Binding,但我无法找到一种方法来在 List 或 ForEach 中获取 NSManagedObject 实例,并将其传递给可以将其用作 @Binding 的视图。
struct TimelineListView: View {
@Environment(\.managedObjectContext) var managedObjectContext
// The Timeline class has an `allTimelinesFetchRequest` function that can be used here
@FetchRequest(fetchRequest: Timeline.allTimelinesFetchRequest()) var timelines: FetchedResults<Timeline>
@State var openAddModalSheet = false
var body: some View {
return NavigationView {
VStack {
List {
Section(header:
Text("Lists")
) {
ForEach(self.timelines) { timeline in
// ?? How to I use the timeline in this list as a …Run Code Online (Sandbox Code Playgroud) 我目前正在学习 SwiftUI,以进一步将其纳入我基于 UIKit 的日常工作流程中。我已经到了无法在 SwiftUI 中运行一个概念的地步,而我已经在 UIKit 中使用了多年。
这个想法是使用我的主 CoreData 的子上下文managedObjectContext来编辑实体。我基本上通过执行以下操作来实现它:
// Get view context of application
let viewContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// Create NSManagedObjectContext
let editingContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
// Set the parent of the editing context to the main view context
editingContext.parent = viewContext
Run Code Online (Sandbox Code Playgroud)
通过使用单独的,editingContext我可以对其中的实体进行更改,而无需将更改直接进行到我的主上下文。如果用户选择中止更改,我只需重置editingContext.
对于 SwiftUI 中的实现,我选择通过创建自定义来将EditingContext实现为环境对象EnvironmentKey:
struct EditingContextKey: EnvironmentKey {
static let defaultValue: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
}
extension EnvironmentValues {
var editingContext: NSManagedObjectContext {
get { …Run Code Online (Sandbox Code Playgroud)