CoreStore icon indicating copy to clipboard operation
CoreStore copied to clipboard

Dynamically create/fetch NSManagedObjects based on the Entity name

Open Guferos opened this issue 8 years ago • 4 comments

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
...

Guferos avatar May 20 '18 12:05 Guferos

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.

JohnEstropia avatar May 21 '18 01:05 JohnEstropia

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?

Guferos avatar May 21 '18 08:05 Guferos

Hmm, I'll need to check again, but import methods should have the same usage of Into<T> clauses.

JohnEstropia avatar May 21 '18 09:05 JohnEstropia

I'm closing this issue for now. Let me know if you this wasn't resolved.

JohnEstropia avatar Jun 10 '18 02:06 JohnEstropia