views:

1785

answers:

2

I'm new to Apple's iPhone 3.0 SDK support of Core Data and I'm relatively new to iPhone development. My question is on slightly more "complex" sorting than is covered in the docs. I suspect that I am making an incorrect, fundamental assumption.

How can I sort a pre-fetched collection of managed objects by a property contained several layers deeper in the collection?

Example: Farm has a 1 to many to Cowboy (Farm.cowboys) Cowboy has a 1 to 1 to Person (Cowboy.person) Person has lastName (Person.lastName)

The entire object graph has been fetched and the cowboys are displayed through a UITableView. Now, how do I sort Cowboys by lastName? Do I need to re-fetch them? and if yes, how do I do this with a nested sort?

Currently I'm trying to sort an NSMutableArray of cowboys ([Farm.cowboys allobjects]) which is fine for those properties on Cowboy. But I am not sure how to make this work when sorting a collection of Cowboys by Cowboy.person.lastName?

A: 

Hopefully someone has a better solution. However....

A wrapper object with a compare selector and a reference to the sort object works. It is not as clean as I would like so hopefully someone else will come up with an alternative.

In essence CowboyWrapper has a cowboy property. CowboyWrapper also has a compare selector. By building and keeping in sync an NSMutableArray of CowboyWrappers, sort works.

guinaut
+3  A: 

If you can target 10.6, you can accomplish this using blocks. Like so:

- (NSArray *)sortedArray {
    return [originalArray sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2){
 NSString *lastName1 = [[obj1 person] lastName];
 NSString *lastName2 = [[obj2 person] lastName];
 return [lastName1 caseInsensitiveCompare:lastName2]; }];
}
Matt Ball
Also worth noting, if you're using an `NSMutableArray`, you can just use `sortUsingComparator:` instead, if you'd like.
Matt Ball