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!