Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Sort an NSMutableArray of Managed Objects through an object graph

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?

like image 917
guinaut Avatar asked Aug 28 '09 18:08

guinaut


2 Answers

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]; }];
}
like image 70
Matt Ball Avatar answered Nov 08 '22 04:11

Matt Ball


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.

like image 5
Chris Avatar answered Nov 08 '22 03:11

Chris