What I want to do seems pretty simple, but I can\'t find any answers on the web. I have an NSMutableArray
of objects, and let\'s say they are \'Person\' objects
I did this in iOS 4 using a block. Had to cast the elements of my array from id to my class type. In this case it was a class called Score with a property called points.
Also you need to decide what to do if the elements of your array are not the right type, for this example I just returned NSOrderedSame
, however in my code I though an exception.
NSArray *sorted = [_scores sortedArrayUsingComparator:^(id obj1, id obj2){
if ([obj1 isKindOfClass:[Score class]] && [obj2 isKindOfClass:[Score class]]) {
Score *s1 = obj1;
Score *s2 = obj2;
if (s1.points > s2.points) {
return (NSComparisonResult)NSOrderedAscending;
} else if (s1.points < s2.points) {
return (NSComparisonResult)NSOrderedDescending;
}
}
// TODO: default is the same?
return (NSComparisonResult)NSOrderedSame;
}];
return sorted;
PS: This is sorting in descending order.