如何在 Swift 5 中不按值设置值将整个对象存储在 CoreData 中?

How to store a whole object in CoreData without setting value by value in Swift 5?

我正在使用 CoreData 开发一个持久性管理器,我打算让它尽可能地可重用。我的第一个想法是开发一个接收通用对象作为参数并使用 CoreData 存储它的函数。 (下面的例子)

func store<T: NSManagedObject>(object: T) {
    let entityName = "\(type(of: object))"
    
    let context = persistentContainer.viewContext
    guard let auditEntity = NSEntityDescription.entity(forEntityName: entityName, in: context) else { return }
    
    let auditToStore = Audit(entity: auditEntity, insertInto: context)
    
    auditToStore.setValue("example value", forKey: "example key")
    
    do {
        try context.save()
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }
}

问题是,据我所知,要将数据保存到 CoreData 中,您必须设置要保存的新项目的每个值,如果该函数假装是通用的,则很难做到。

非常感谢。

经过一些研究,我找到了答案并想出了如何创建一个方法来存储通用 NSManagedObjects。

/// This method stores an object of a generic type that conforms to NSManagedObject
func insert<T: NSManagedObject>(object: T) {
    let context = persistentContainer.viewContext
    
    context.insert(object)
    
    do {
        try context.save()
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }
}