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
427 views
in Technique[技术] by (71.8m points)

iphone - Core data: any way to fetch multiple entities?

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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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


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

...