Home > Software design >  How to store a whole object in CoreData without setting value by value in Swift 5?
How to store a whole object in CoreData without setting value by value in Swift 5?

Time:12-06

I'm developing a persistance manager using CoreData and I have the intention of making it as reusable as possible. My very first idea was to develop a function that receives a generic object as parameter and store it using CoreData. (example below)

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)")
    }
}

The trouble is that as far as I know, for saving data into CoreData you have to set every value of your new item to save and if the function pretends to be generic it would be very difficult to do it.

Thanks a lot.

CodePudding user response:

After some research I found the answer and figured out how to create a method to store generic 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)")
    }
}
  • Related