Ios – Core data: any way to fetch multiple entities

core-dataiosiphone

I'm just getting started with Core Data, and as a learning exercise I'm building an app where I need to display different types of objects in a single table view.

As an example, say I have an entity for "Cheese" and an unrelated entity for "Pirate". On the main screen of my app, the user should be able to create either a "Cheese" or a "Pirate" instance to add to the table view.

So, using the core data editor I've created entities for Cheese and Pirate… however, an NSFetchRequest seems to only allow you to retrieve one type of entity at a time with:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Cheese" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];

Is there any way to perform a fetch that retrieves all "Cheese" and "Pirate" objects?

Thanks.

Best Answer

What you're trying to do is accomplished by defining entity inheritance in your model, where "DisplayableObject" would be an abstract class defined as the parent of "Cheese" and "Pirate".

Then you can perform a fetch request on the "DisplayableObject" entity and it will retrieve both entities' objects.

Take a look into this article in the apple documentation: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/KeyConcepts.html

Related Topic