开发者

Traversing one-to-many relationships with NSFetchedResultsControllers

I am creating an app that navigates through multiple levels of one-to-many relationships. So for example, pretend that the CoreDataBooks code sample starts with a list of genres, you click on a genre and 开发者_开发知识库then get the list of books organized by author as seen in Apple's code sample.

Here is my problem: the Apple documentation tells me I should use a FetchedResultsController to help organize my list of books into sections (among other reasons). But when trying to figure out how to get from "one" genre to my "many" books, the Core Data FAQ tells not to use a fetch. From the FAQ:

I have a to-many relationship from Entity A to Entity B. How do I fetch the instances of Entity B related to a given instance of Entity A?

You don’t. More specifically, there is no need to explicitly fetch the destination instances, you simply invoke the appropriate key-value coding or accessor method on the instance of Entity A.

The problem, of course, is I now have my books in a set, but I want them to get them from a fetched results controller.

What is the best way to proceed here? Should I follow the FAQ, and if so, how do I manage dividing my books up into sections by author?

Or do I use a fetched results controller (which I suspect is better), in which case how do I traverse the one-to-many relationship (since Apple's oh-so-helpful answer is simply "don't")?

Many thanks for your help.

Sasha


You have a data model that looks roughly like this:

Genre{
  name:
  books<-->>Book.genre
}

Book{
  name:
  genre<<-->Genre.books
}

In your master table, you run a fetched results controller to get table of Genre objects. Then the user selects one of the row which behind the scenes selects a particular Genre object.

Since every Genre object has a books relationship that points to the related Book objects, you have automatically got a reference to all the related book objects so you don't have to fetch anything. For your book tableview you just create a sorted array of the Book objects in the selected Genre object's books relationship.

Think of a Core Data object graph as a clump of bead strings all woven together in a web or fabric. The beads are objects and the strings are relationships. A fetch plucks one of the bead/objects from the clump but once you have that bead/object in hand, then you can just pull on its string/relationship to pull out all the beads/objects related to the bead in your hand.

So, fetches are used in most cases just to find the starting objects, then you walk relationships to find most of the other objects.

That is why the Apple docs say you don't need a second fetch.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜