Sorting array of objects by two criterias?
I have an array of objects that i want to sort by two keys. The objects lets say are of type Student and the properties that i'm intrested in for my sort are grade and name.
Student
{
double grade;
string name;
...
}
How can i sort the 开发者_运维技巧objects first by grade and then by name? so for example if i have the list: Tom 9.9 Andrew 9.8 Chriestie 10 Mat 9.8 Allison 10 Ada 9.8
After the sort i should have: Allison 10 Christie 10 Tom 9.9 Ada 9.8 Andrew 9.8 Mat 9.8
And not Christie 10 Allison 10 Tom 9.9 Andrew 9.8 Ada 9.8 Mat 9.8
any pointer is really helpful.
I'm pretty flakey on my objective-c knowledge but there's some good pointers here and there's always the documentation. Here's my crack at it...
NSSortDescriptor *gradeSorter = [[NSSortDescriptor alloc] initWithKey:@"grade" ascending:YES];
NSSortDescriptor *nameSorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[personList sortUsingDescriptors:[NSArray arrayWithObjects:gradeSorter, nameSorter, nil]];
You basically need to implement your own comparator and use one of NSArray
sort methods (e.g. sortedArrayUsingSelector:
)
-(NSComparisonResult)compare:(Student *)student {
// sort by name
int nameComp = [name compare:student.name];
if (nameComp != NSOrderedSame) return nameComp;
// reverse ordered as desired in the question
if (grade > student.grade)
return NSOrderedAscending;
else if (grade == student.grade) // watchout here
return NSOrderedSame;
else
return NSOrderedDescending;
}
NSArray *unsrtedArray = ...
NSArray *sortedArray = [unsortedArray sortedArrayUsingSelector:@selector(compare:)];
_pScheduleArr : The name of array in my below code. This array contains the custom model object. I compare the array on behalf of date and alphabetical order. Date is also present in the array inside array(core data model).
_pScheduleArr = [[_pScheduleArr sortedArrayUsingComparator:^NSComparisonResult(Meetings *obj1, Meetings *obj2) {
NSOrderedSet *personSetObj1 = obj1.timeSlots;
Timeslot *tt1 = [[personSetObj1 array] objectAtIndex:0];
NSOrderedSet *personSetObj2 = obj2.timeSlots;
Timeslot *tt2 = [[personSetObj2 array] objectAtIndex:0];
NSDate *date11 = tt1.startTime;
NSDate *date12 = tt2.startTime;
NSComparisonResult comresult = [date11 compare:date12];
if (comresult == NSOrderedSame) {
comresult = [obj1.title compare:obj2.title];
}
return comresult;
}] mutableCopy];
精彩评论