重新调用swifui视图会导致NSManagedObject在托管对象上下文中重复– CoreData

问题描述

我想使用核心数据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

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...