Dynamically create/fetch NSManagedObjects based on the Entity name
I have a case where I need to deserialize JSON into the Core Data objects and I tried to find a way to dynamically create/fetch objects based on their entity name string. The CoreStore API uses generics to create/fetch objects therefore the NSManagedObject subclass must be known. I thought about using native CoreData methods but it is not possible to access the NSManagedObjectContext from the transaction. Is there any way to create objects dynamically using string as the entityName and get the generic NSManagedObject? Something like:
...
let object = transaction.create(intoEntityName: "User") // returns NSManagedObject
...
You can manage the static and dynamic typing of fetches using this special Into initializer:
let object = transaction.create(Into<NSManagedObject>(User.self)) // returns NSManagedObject
The generic type can be NSManagedObject or any of its subclass, and you need to make sure that the dynamic type passed into the argument is any subclass of that generic type. The fetch result will always use the dynamic type.
John, thanks for a very quick reply. I somehow missed that extra initializer. Is there any way to do the same when using the importUniqueObject: method or this cannot be achieved due to associatedType constraint?
Hmm, I'll need to check again, but import methods should have the same usage of Into<T> clauses.
I'm closing this issue for now. Let me know if you this wasn't resolved.