I have a complex core data mapping in my app, simplified to the relevant pats to this question here in this image:
alt text http://grab.by/2aLT
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:
- Fetch a list of all categories, sorted by name
- For each category, fetch the Sorted Foos, sorted by index ascending
- For each SortedFoo, fetch the associated Foo, stick in an array
- Take the Foos, now sorted by index in an array, and add this array to a 2D array
- 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?
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];
精彩评论