0

I have an NSMutableDictionary that contains keys that are NSStrings, and values that are objects of type "Fraction". This is a custom object that I have created and is exactly what it is, Fractions that are composed of a numerator, and a denominator (each one is an int). What I would like to do is get an array of the values (in this case, "Fraction" objects) from the NSMutableDictionary, and then sort the array using @selector as follows:

NSArray *myFractions = [myDict allValues];
NSArray *sortedFractions = [myFractions sortedArrayUsingSelector:@selector(comparator)];

or

NSArray *myFractions = [myDict allValues];
NSArray *sortedFractions = [myFractions sortedArrayUsingFunction:comparatorFunction context:nil];

My question is, how do I create a comparatorFunction method that will sort the "Fraction" objects in order of biggest, to smallest? Please remember that each "Fraction" object is composed of two variables: a numerator of type int, and a denominator that is also of type int.

This question is different from others that have been posted because here I am asking about how, within the "sortedArrayUsingFunction" method I am to sort the "Fraction" objects from greatest to least. The other questions that were thought to be duplicates were looking at sorting based on NSDate objects, or based on NSString values, whereas mine is different. As I said, I am very new to this, and needed something much more specific.

Thanks in advance.

syedfa
  • 2,801
  • 1
  • 41
  • 74

2 Answers2

0

In your class you need to implement a method similar to this :

-(NSComparisonResult)compareFirstName:(Fraction *)fraction{

      return ((float)self.numerator/self.denominator > (float)fraction.numerator/fraction.denominator);
}

*Not compiled and checked

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
0

As a stylistic improvement, can I suggest you to use a closure instead of a function? To sort the objects in descending order, simply compare their actual numerical value, like this:

NSMutableDictionary *dict = // dictionary of NSString keys and Fraction values
NSArray *fractions = [dict allValues];

NSArray *sortedFractions = [fractions sortedArrayUsingComparator:^(id obj1, id obj2) {
    Fraction *f1 = obj1;
    Fraction *f2 = obj2;
    double diff = (double)(f1.num) / f1.denom - (double)(f2.num) / f2.denom;
    return diff < 0 ? NSOrderedAscending : diff > 0 ? NSOrderedDescending : NSOrderedSame;
}];