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?
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]; }];
}
You can sort like so:
[myUnsortedArrayOfCowboys sortedArrayUsingDescriptors:
[NSArray arrayWithObject:
[NSSortDescriptor
sortDescriptorWithKey:"person.lastName"
ascending:YES]]];
Notice the '.' in the sort descriptor key. This is how you traverse the object graph.
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