Core Data: Abstract Entity in Fetch Request

Viewed 7167

Suppose I have a Core Data model with an abstract entity called "Animal." Then, I have many other entities that inherit from this abstract entity: "Lion", "Dog", "Cat", etc. (I'm not developing a zoo program, but this analogy works well for the issue I'm explaining!)

What I want to know is: Can I fetch "all animals" at once by doing this:

NSFetchRequest *searchRequest = [[NSFetchRequest alloc] init];
[searchRequest setEntity:[NSEntityDescription entityForName:@"Animal" inManagedObjectContext:aContext]];

NSArray *matchedObjects = [aContext executeFetchRequest:searchRequest error:nil];

I understand there are methods on NSEntityDescription to determine whether an entity inherits from another. But is there a fast way to grab all entities that are of a particular (abstract) type --- in this case, "Animal"?

If the approach above is invalid, what is the most efficient way to go about this? Thanks!

3 Answers

Yes, I believe you can fetch all the Animals at once.

From the Core Data Programming guide:

Entity Inheritance

If you specify a parent entity in Core Data as the entity for a Core Data fetch request, the fetch returns matching instances of the entity and subentities (see Fetching Objects). As a corollary, if you specify a parent entity as the entity for a controller that is backed by Core Data, it fetches matching instances of the entity and any subentities. If you specify an abstract parent entity, the Core Data backed controller fetches matching instances of concrete subentities.

Related