How to convert struct to Core Data NSManagedObject

Issue #706

Use Mirror and set key value as NSManagedObject subclasses from NSObject

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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

Comments