Issue #706

Use Mirror and set key value as NSManagedObject subclasses from NSObject

import CoreData

final class ManagedObjectConverter {
    func convert<M>(m: M, context: NSManagedObjectContext) throws -> NSManagedObject {
        let entityName = String(describing: m)
        guard let entityDescription = NSEntityDescription.entity(
            forEntityName: entityName,
            in: context
        ) else {
            throw AppError.parsing
        }

        let managedObject = NSManagedObject(
            entity: entityDescription,
            insertInto: context
        )

        let mirror = Mirror(reflecting: m)

        guard mirror.displayStyle == .struct else {
            throw AppError.parsing
        }

        for case let (label?, anyValue) in mirror.children {
            managedObject.setValue(anyValue, forKey: label)
        }

        return managedObject
    }
}

Updated at 2020-12-07 06:05:04