0

当我myArray使用[myArray sortArrayUsingSelector: @selector(comparison:)]; fracC不与比较进行排序时fracA,所以现在(1/2)按从最大值到最小值的顺序fracA放在(1/4) 之后。fracC有没有办法让所有元素正确地相互比较,如果我想添加更多值,它仍然可以工作?

比较:

-(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;
    }
}

比较:输出

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

主文件

        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);
        }

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

比较:

-(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;
}
4

1 回答 1

2

sortedArrayUsingSelector:返回一个的排序数组(您丢弃)。

您可能想要使用sortUsingSelector:which 对数组的元素进行适当的排序。

于 2012-08-03T21:33:28.183 回答