views:

229

answers:

1

I have a complex core data mapping in my app, simplified to the relevant pats to this question here in this image:

alt text

My question is how to get sorted Foo's efficiently. Let's say that in one of my views, I have a sectioned table with every foo in it. The sections are the categories. Each section of foo (in a category) has an ordering.

Now, I am fetching them using this algorithm:

  1. Fetch a list of all categories, sorted by name
  2. For each category, fetch the Sorted Foos, sorted by index ascending
  3. For each SortedFoo, fetch the associated Foo, stick in an array
  4. Take the Foos, now sorted by index in an array, and add this array to a 2D array
  5. Return the 2D array as the ordered foo's in each alphabetized category.

This seems soooooo inefficient to me. Surely there must be a better way to do this common type of fetch. Can anybody suggest a new way to do this?

A: 

I would make the foo sort index universal across categories. Then, fetch all Foo objects sorted by the index.

If you were using a fetched results controller, you would then use the Category name as the section name key path. If not, you can just partition them by the Category name manually.

UPDATE
Actually, keeping index the way you have it, you could fetch all Foo objects and sort first by Category and then by SortFoos index. You would still need to partition them by the Category name manually.

UPDATE 2
For example:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sorted_positions.category.name" ascending:YES];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"sorted_positions.index" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, sortDescriptor2, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
gerry3
could you give a quick code sample of what you mean by the UPDATE part?
coneybeare
I ended up scrapping the whole ordered in a category thing and am just organizing by name. Make my life, and code, much easier
coneybeare
I added a code example anyway.
gerry3