当我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;
}