在模式视图中编辑特定的核心数据对象

时间:2020-04-30 22:01:26

标签: core-data swiftui

在我的核心数据学习中,我现在坚持以下几点: 我在ContentView中显示核心数据对象的列表。 如果用户要编辑其中之一,则可以长按列表中的项目,该项目会弹出带有和编辑按钮的上下文表。到现在为止还挺好。 编辑按钮会召唤一个模式视图,在该视图上进行编辑。

在“编辑”视图中,我首先通过存储在UserDefaults中的UUID属性获取正确的项目。

我能够显示商品的名称,但是我遇到了日期问题(该商品具有“ eventDate”日期属性。

该应用程序可以构建,我可以在设备上运行它,但是一旦尝试编辑项目,它就会崩溃。当我实例化选择器要显示给事件日期的值时,在EditView代码中引发错误:The error

这是编辑按钮内的内容:

Button(action: {
      self.modalViewCaller = 1 // To tell the sheet which view to display
      UserDefaults.standard.set(item.identNumber?.uuidString, forKey: kactiveEventUUID)
      self.settingsModalIsPresented = true
                })
                 {   Text("Edit entry")
                    Image(systemName: "globe")
                }

以及我在EditView中获取事件的方式:

@Environment(\.managedObjectContext) var managedObjectContext

    // We get the event to be edited through its UUID :
    @FetchRequest(entity: Takeoffs.entity(),
                  sortDescriptors: [NSSortDescriptor(keyPath: \Takeoffs.eventDate, ascending: false)],
                  predicate: NSPredicate(format: "identNumber == %@", UUID(uuidString: UserDefaults.standard.string(forKey: kactiveEventUUID)!)! as CVarArg)) var fetchedEvent: FetchedResults<Takeoffs>
        // UserDefaults.standard.object(forKey: kactiveEventUUID) as! CVarArg)

    @State var selectedDate = Date()

    init() { // This sets "selectedDate" to the event's value for the date picker
        _selectedDate = State(initialValue:  fetchedEvent.first?.eventDate ?? Date()) // The underscore is used here
    }

如果有人有勇气,可以在这里使用该项目:https://github.com/Esowes/RecentExp

感谢您的帮助...

[编辑:]尝试以下建议的.didAppear解决方案,但似乎找不到在我体内接受.didAppear的视图:

        var body: some View {
            NavigationView {
                Form {
                    HStack {
                        Text("Airport : ")
                        TextField(String(fetchedEvent.first?.airportName ?? ""), text: $airportNameTextfield)
                        .disabled(airportNameTextfield.count > 2) // To limit the textField to 3 chars (IATA code)
                        Button(action: {
                            self.airportNameTextfield = ""
                        }) {
                            Image(systemName: "clear")
                            }
                    } // END of Hstack
                    Picker("", selection: $typeSelectorIndex) {
                          ForEach(0 ..< types.count) { index in
                              Text(self.types[index]).tag(index)
                          }
                      }
                      .pickerStyle(SegmentedPickerStyle())
                    //  Text("Selected type is: \(types[typeSelectorIndex])")
                    VStack {
                        Button(action: {
                            self.selectedDate = Date()
                        }) {
                            Text("Today")
                        }
                        DatePicker("",selection: $selectedDate, displayedComponents: .date)
                            .padding(30)
                            .labelsHidden()
                    }
                } // END of Form
                .navigationBarItems(
                    leading:
                    Button("Done") {
                        self.saveEdits()
                        self.presentationMode.wrappedValue.dismiss() // This dismisses the view
                    } // END of Button "Done"
                )
                .navigationBarTitle("Event edition")
            } // END of Navigation View
        } // END of some View

1 个答案:

答案 0 :(得分:1)

fetchedEvent在通话View.init尚不可用,因此请像下面这样在.didAppear中使用

// ... remove that init at all

var body: some View {
    Text("Any internal view here")    
    .onAppear {
        // assigned fetched event data, here it is available
        self.selectedDate = self.fetchedEvent.first?.eventDate ?? Date()
    }
}