Is there a bulit-in way to obtain an entity name from the class object of an NSManagedObjectSubclass? I know that this can be readily determined from an instance of a subclass, but I want to ask the class itself. I can write a class function, but I would rather do this introspectively.
Asked
Active
Viewed 4,899 times
16
-
There is no built-in method, but this answer provides a possible solution: http://stackoverflow.com/a/14049649/1187415 – Martin R Jan 08 '13 at 19:57
-
thanks. my class names are not the same as my entityNames, so I've not used this approach: for now, i'm just passing constant strings from a class function adopted by all my classes. – pickwick Jan 08 '13 at 20:08
-
The `entityName` class method from rob mayoff's answer is exactly for that case: it retrieves the entity name from the entity descriptions in the core data model. – Martin R Jan 08 '13 at 20:14
-
you are right; i didn't look past what he did at the top. thanks – pickwick Jan 08 '13 at 20:42
-
2If you are happy with that answer we can close this as a duplicate of http://stackoverflow.com/questions/14049592/does-nsstringfromclassmyentityclass-class-generate-a-safe-core-data-entity-n. – Martin R Jan 08 '13 at 21:03
-
ok; go ahead and close it – pickwick Jan 09 '13 at 21:32
2 Answers
7
You can do it now by executing NSManagedObject.entity().name
where NSManagedObject()
is your subclass.

Vasily
- 3,740
- 3
- 27
- 61
-
2Which is actually optional and is not a reliable source. I've had multiple occasions where .entity().name returned nil while I invoked it on a subclass of NSManagedObject that should've had an entity. I would not recommend relying on this. – Mark Sep 06 '18 at 14:45
-
It returns optional, so you always need to check a provided value before unwrapping. You could propose other ways to get that name. – Vasily Apr 21 '19 at 14:14
-
1@Vasily mark is right. For some strange reason nil is returned by `.name`. And if you are going to check before unwrapping and then passing the alternative, you might as well just specify the alternative in the first place. – pnizzle Oct 31 '19 at 10:33
0
Check out mogenerator if you haven't already. http://raptureinvenice.com/getting-started-with-mogenerator/
It adds a lot of missing features to core data. In particular it keeps you from having to regenerate your entity classes.
You could iterate thru the key values of the entities in the context:
[managedObjectContext registeredObjects];

SpaceTrucker
- 1,168
- 7
- 16