Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

iphone sdk 3.0 - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]; }];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...