就我而言,我有一个ContactProfile
要更新的视图。我认为制作联系人实体的副本,编辑副本,然后将副本的属性“粘贴”回原始实体,然后将其保存在managedObjectcontext
.
到目前为止,我的代码仅tempContact
引用了原始联系人。这是有道理的,因为原始联系人是 CoreData 生成的类,而不是结构。
解决这个问题的最佳方法是什么?还是我想太多了?本身是否@ObservedObject
足以进行编辑,因为直到通过private func saveContext()
稍后在代码中显式调用函数才将其保存到数据库中?
到目前为止,我有这个代码:
struct ContactProfile: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Level.sortOrder, ascending: true)],
animation: .default)
private var levels: FetchedResults<Level>
@ObservedObject var contact: Contact
/// Old code
/// @State private var tempContact: Contact
/// init(contact: Contact){
/// _contact = ObservedObject(initialValue: contact)
/// _tempContact = State(wrappedValue: contact)
/// }
///updated code below:
@State private var tempContact = TempContact(firstName: "", lastName: "", birthDate: Date(), picture: nil)
init(contact: ObservedObject<Contact>) {
_contact = contact
_tempContact = State(initialValue: tempContact)
tempContact.firstName = contact.wrappedValue.firstName ?? ""
tempContact.lastName = contact.wrappedValue.lastName ?? ""
}
///end of updated code
var body: some View {
Form {
Text("@Observed: \(contact.firstName ?? "Unknown") \(contact.lastName ?? "Unknown")")
Text("@State: \(tempContact.firstName ?? "Unknown") \(tempContact.lastName ?? "Unknown")")
TextField("Enter name", text: Binding(
get: { self.tempContact.firstName ?? ""},
set: { self.tempContact.firstName = $0 }
)
)
[snipped the rest of the normal view code]
可以这样ContactProfile
访问ContactsList
:
struct ContactsList: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Contact.lastName, ascending: true)],
animation: .default
)
private var contacts: FetchedResults<Contact>
var body: some View {
List {
ForEach(contacts) { contact in
NavigationLink(
destination: ContactProfile(contact: contact)) {
HStack (alignment: .firstTextBaseline) {
Text("\(contact.firstName ?? "Unknown") \(contact.lastName ?? "Unknown")")
Text("(\(contact.level?.name ?? ""))").font(.caption).foregroundColor(.gray)
}
}
}
.onDelete(perform: deleteContacts)
}
.listStyle(PlainListStyle())
.navigationTitle("Contacts")
.navigationBarItems(trailing: Button(action: addContact) { Image(systemName: "plus") }
)
}
[snip]