我想使用核心数据NSManagedObject作为观察对象,以供用户编辑。问题在于,重新调用基础swiftui视图会导致托管对象上下文中的托管对象重复,因为其重复初始化。解决该问题的最优雅方法是什么? (为了便于以后编辑保存的对象,我想使用这种观察到的管理对象方法)
struct ContentView: View {
@FetchRequest(entity: ProtocolParent.entity(),sortDescriptors: []) var savedProtocols: FetchedResults<ProtocolParent>
@State var showAddView = false
var body: some View {
VStack {
Button(action: {
self.showAddView.toggle()
}) {
Text("Add Protocol")
}
List {
ForEach(savedProtocols,id: \.self) { element in
Text(element.name)
}
}
.sheet(isPresented: $showAddView) {
AddProtocolParentView()
}
}
}
}
struct AddProtocolParentView: View {
@ObservedObject var vm = AddProtocolParentViewModel()
var body: some View {
VStack {
TextField("AddName",text: $vm.protocolParent.name)
Button(action: {
self.vm.save()
}) {
Text("Save")
}
}
}
}
class AddProtocolParentViewModel: ObservableObject {
var moc: NSmanagedobjectcontext
@Published var protocolParent: ProtocolParent
init() {
moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
protocolParent = ProtocolParent(context: moc)
protocolParent.name = ""
}
func save() {
do {
try moc.save()
print("Saved!")
} catch {
print(error.localizedDescription)
}
}
}
CoreData类(名称设置为非可选):
extension ProtocolParent {
@nonobjc public class func fetchRequest() -> NSFetchRequest<ProtocolParent> {
return NSFetchRequest<ProtocolParent>(entityName: "ProtocolParent")
}
@NSManaged public var name: String
}