开发者

Core data: any way to fetch multiple entities?

I'm just getting starte开发者_高级运维d 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.


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


I had to deal with this issue as well. Wanted to be able to search multiple entities but avoid inheritance that results in hierarchy of objects all stored in a single core data class and the performance issues that may result.

I opted for creating a concrete Searchable object that stores searchable terms common among the objects I want to search against. This object was added to each of the classes I wanted to search for:

Person.Searchable
Employee.Searchable
Department.Searchable

Searchable has fields such at searchTerm and to many relationships with each of the objects I need to search for. And a displayName so that the information can be shown to the user without having to query/load any other table.

Core Data queries are executed against Searchable so you only query a single entity.

Example:

Person { firstName = Joe, lastName = Jackson } -> searchable { term = joejackson, displayName = Joe Jackson, type = person }
Employee { firstName = Joe, lastName = Smith } -> searchable { term = joesmith, displayName = Joe Smith, type = employee }
Group { name = Joe’s Development Team } -> searchable { term = joesdevelopmentteam, displayName = Joe’s Development Team, type = group }

Now you can list and search for Person, Employee, Department all separate tables using their Searchable member using a single Fetched Request Controller.


Tiago's answer is valid but the most straight forward way of doing this is performing two separate fetch requests and you can either store in separate NSArrays or append to one mutable array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜