2

This is not a how do I do this post. Instead, I want to understand how it works and hopefully others can learn too.

For this example, let's say I have an NSMutableArray with NSDecimalNumber objects in them. Let's say the objects inside, in no particular order, are [-464.50, +457.20, 0, -1000]. Prior to comparing them, I apply the absolute value to them.

In my code, I use the sortUsingComparator method and give it a block. I started testing the different conditions and here is the result as they are presented in a UITableView:

return [person1Amount compare:person2Amount];
==> 0, 457.20, -464.50, -1000

If,

return [person2Amount compare:person1Amount];
==> -1000, -464.50, +457.42, 0

How does the compare: method actually works. The NSDecimalNumber doc here does not really explain it to me. This part especially confuses me:

Return Value NSOrderedAscending if the value of decimalNumber is greater than the receiver; NSOrderedSame if they’re equal; and NSOrderedDescending if the value of decimalNumber is less than the receiver.

Does that mean that the order of objects inside the array determines how it is sorted? For example, if person1.number < person2.number, it will sort array in ascending order? Why does my code [person2Amount compare:person1Amount] yield the right results?

It looks like person2Amount is < person1Amount and so it sorts it descending but if person2Amount is > person1Amount, then it will sort is in ascending?

My understanding does not seem right.

Thanks!

4

2 回答 2

2

看来您已经回答了自己的问题。

return [person1Amount compare:person2Amount];

对比

return [person2Amount compare:person1Amount];

考虑以上两个陈述;该compare:方法返回NSOrderedAscendingNSOrderedDescending取决于两个对象中的哪一个大于另一个。

如果你要这样做:

return [@1 compare:@2];

对比

return [@2 compare:@1];

NSOrderedAscending然后你会收到NSOrderedDescending什么应该是显而易见的原因。

因此,如果您实现自己的compare:方法并切换用于比较的两个对象(如上面@1 与@2 的情况),您将有效地反转数组的排序顺序。

于 2013-04-21T22:45:17.383 回答
1

由于您正在比较绝对值,因此让我们忽略这些符号。您的数字是 464.50、457.20、0 和 1000。升序表示数字变大,因此顺序为 0、457.20、464.50、1000。降序表示它们变小,因此顺序为 1000、464.50、457.20、 0。

使用比较器时,数组会根据比较器升序排序。它将成对的值发送到比较器。如果比较器返回它们按升序排列,它将第一个放在第一位。如果它返回它们是按降序排列的,它将第二个放在第一位。

NSNumbercompare:方法的工作原理基本上是这样的(当然你不能在 NSNumbers 上使用>and <,但它的想法):

- (NSComparisonResult)compare:(NSNumber *)number2 {
    if(self < number2) return NSOrderedAscending;
    if(self > number2) return NSOrderedDescending;
    return NSOrderedSame;
}

因此,如果您的比较器调用[number1 compare:number2],如果数字是升序的(数字 1 较小),结果将是升序的,这意味着它们将保持该顺序并在数组中升序。如果比较器切换它们,[number2 compare:number1]如果数字下降(数字 2 较小),则结果将上升,因此它们将被切换并在数组中下降。

于 2013-04-21T22:53:59.277 回答