Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting toMany relationship Set in core data

I have Two models Department and Worker. Departments has to-many relationship(workers) to worker. Worker has firstName field. How can i get a worker list sorted by firstName by accessing departmet.workers? Is there any way to add sort descriptors in to-many relationship?

like image 714
user159439 Avatar asked Aug 19 '09 17:08

user159439


1 Answers

Minor improvement over Adrian Hosey's code:

Instead of manually iterating over all workers you can also just do:

-(NSArray *)sortedWorkers {   NSSortDescriptor *sortNameDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES] autorelease];   NSArray *sortDescriptors = [[[NSArray alloc] initWithObjects:sortNameDescriptor, nil] autorelease];    return [self.workers sortedArrayUsingDescriptors:sortDescriptors]; } 

Probably does exactly the same thing as your iteration internally, but maybe they made it more efficient somehow. It's certainly less typing…

Note: the above only works on iOS 4.0+ and OSX 10.6+. In older versions you need to replace the last line with:

  return [[self.workers allObjects] sortedArrayUsingDescriptors:sortDescriptors]; 
like image 58
Adrian Schönig Avatar answered Sep 19 '22 17:09

Adrian Schönig