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 want to sort number and string then use this
NSArray *unsortedArray = [NSArray arrayWithObjects:@"Hello", @"4", @"Hi", @"5", @"2", @"10", @"1", nil];
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id firstObject, id secondObject) {
return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
}];
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.
来源:https://stackoverflow.com/questions/1348748/how-to-sort-an-nsmutablearray-of-managed-objects-through-an-object-graph