myArray
を使用してソートすると、[myArray sortArrayUsingSelector: @selector(comparison:)];
fracC
と比較されfracA
ないため、fracA
(1/2) はfracC
(1/4) の後ろに最大値から最小値の順に配置されます。すべての要素を相互に正しく比較して取得し、さらに値を追加したい場合でも機能する方法はありますか?
比較:
-(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
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);
}
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;
}