Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

objective c - Core Data: Abstract Entity in Fetch Request

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can definitely use that approach.

From Apple's Core Data Programming guide:

Entity inheritance works in a similar way to class inheritance; and is useful for the same reasons. If you have a number of entities that are similar, you can factor the common properties into a superentity, also known as a parent entity. Rather than specifying the same properties in several entities, you can define them in one entity, and the subentities inherit them. For example, you might define a Person entity with attributes firstName and lastName, and subentities Employee and Customer, which inherit those attributes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...