Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSComparator?

I would like to know if the below question is possible using NSComparator or not?

I have two arrays; both hold data models. I have a property named rank in the data model. Now I want to compare both arrays and want to know if one of them holds higher ranked data models. If Yes I would like to get NSComparisonResult = NSOrderedAscending.

By the way I'm using another approach here: is "total of each data Model's rank in array and if the total is greater than second array's data Model's total rank."

like image 912
Rahul Vyas Avatar asked Feb 21 '11 09:02

Rahul Vyas


1 Answers

Yes, it would look something like this:

NSArray *someArray = /* however you get an array */    
NSArray *sortedArray = [someArray sortedArrayUsingComparator:^(id obj1, id obj2) {
  NSNumber *rank1 = [obj1 valueForKeyPath:@"@sum.rank"];
  NSNumber *rank2 = [obj2 valueForKeyPath:@"@sum.rank"];
  return (NSComparisonResult)[rank1 compare:rank2];
}];

(updated to show actually using the comparator)

like image 195
Samuel Goodwin Avatar answered Oct 18 '22 02:10

Samuel Goodwin