views:

400

answers:

2

So if I have a store of parents children and the parent has a one to many relationship to children (parent.children) and they all have first names. Now, on the initial fetch for parents I can specify a sort descriptor to get them back in order of first name but how can I request the children in order? If I do a [parent.children allObjects] it just gives them back in a jumble and I'd have to sort after the fact, every time.

Thanks, Sam

+3  A: 

Sam,

If I read your question correctly, you want to set up a fetch that returns a sorted list of the children of a specific parent. To do this, I would set up a fetch for "children" entities and then use a predicate to limit the results:

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"children" inManagedObjectContext:moc]];
[request setSortDescriptors:[NSArray initWithObject:[[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES]];
[request setPredicate:[NSPredicate predicateWithFormat:@"(parent == %@)", parent]];

Obviously, your entity and attribute names may be different. In the last line, the parent variable should be a reference to the NSManagedObject instance of the parent whose children you want.

Tim Isganitis
I see, you're suggesting running a fetch instead of just using the fault in coredata? Is that less performant? ie is setting up a fetch with the predicate and running it more expensive than just doing [parent.children allObjects] and letting the managedObject fill the fault?
Shizam
I think you are correct that running a whole new fetch request will be slower than filling the fault with [parent.children allObjects] and then sorting the NSArray that you get. In my mind, the advantage of a new fetch request is that you could use an NSFetchedResultsController to keep the result set updated and sorted (i.e. if you create a new child of the parent, it will automatically insert it into the result list). If you plan on keeping the list of children around for any length of time and the list could change (i.e. you are displaying an editable list) I would use this strategy.
Tim Isganitis
+2  A: 

If you just want to use an NSArray, and not an NSFetchedResultsController, there's another way:

NSSortDescriptor *alphaSort = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES];
NSArray *children = [[parent.children allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:alphaSort]];
eman