stumped
stumped

Reputation: 3293

sortUsingSelector: method isn't cycling through all the elements in my array

When I sort myArray using [myArray sortArrayUsingSelector: @selector(comparison:)]; fracC doesnt get compared with fracA, so now fracA (1/2) is placed behind of fracC(1/4) in order of greatest value to lowest. Is there a way to get all the elements compared to each other correctly and for it to still work if I wanted to add more values in?

comparison:

-(NSComparisonResult) comparison:(Fraction *)myFrac {
    NSLog(@"self: %@", self);
    NSLog(@"argument: %@", myFrac);

    if ([self compare: myFrac] == 1) {
        NSLog(@"ascending");
        NSLog(@" ");
        return NSOrderedAscending;
    }
    else if ([self compare: myFrac] == -1) {
        NSLog(@"descending");
        NSLog(@" ");
        return NSOrderedDescending;
    }
    else {
        NSLog(@"same");
        NSLog(@" ");
        return NSOrderedSame;
    }
}

comparison: output

2012-08-03 16:25:43.459 prog[1083:707] self: 1/3
2012-08-03 16:25:43.462 prog[1083:707] argument: 1/2
2012-08-03 16:25:43.463 prog[1083:707] descending
2012-08-03 16:25:43.463 prog[1083:707]  
2012-08-03 16:25:43.464 prog[1083:707] self: 1/3
2012-08-03 16:25:43.464 prog[1083:707] argument: 1/4
2012-08-03 16:25:43.465 prog[1083:707] ascending

main.m

        Fraction *fracA = [[Fraction alloc] initWithValues:1 over:2];
        Fraction *fracB = [[Fraction alloc] initWithValues:1 over:3];
        Fraction *fracC = [[Fraction alloc] initWithValues:1 over:4];

        NSMutableArray *myArray = [NSMutableArray arrayWithObjects:fracB, fracA, fracC, nil];

        [myArray sortArrayUsingSelector: @selector(comparison:)];

        for (Fraction *myFrac in myArray) {
            NSLog(@"%@", myFrac);
        }

output of main.m

2012-08-03 16:25:43.467 prog[1083:707] 1/3
2012-08-03 16:25:43.467 prog[1083:707] 1/2
2012-08-03 16:25:43.468 prog[1083:707] 1/4

compare:

-(int) compare:(Fraction *)f {
    Fraction *selfTester = [[Fraction alloc] init];
    Fraction *fTester = [[Fraction alloc] init];

    selfTester.denominator = self.denominator * f.denominator;
    selfTester.numerator = f.denominator * self.numerator;

    fTester.denominator = self.denominator * f.denominator;
    fTester.numerator = f.numerator * self.denominator;


    if (selfTester.numerator < fTester.numerator)
        return -1;
    else if (selfTester.numerator == fTester.numerator)
        return 0;
    else
        return 1;
}

Upvotes: 0

Views: 111

Answers (1)

Martin R
Martin R

Reputation: 539975

sortedArrayUsingSelector: returns a new sorted array (which you discard).

Your probably want to use sortUsingSelector: which sorts the elements of the array in place.

Upvotes: 2

Related Questions