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?
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With