Take the 2-minute tour ×

I'm trying to understand what the standard way of writing a compare function is.

If I have an object Person with a property age and want to write my own compare function. I want to use it so that the Person objects are ordered from low age to high age.


Person *young = [[Person alloc] initWithAge:10];
Person *old = [[Person alloc] initWithAge:80];

If I now run [young compare:old] should this return NSOrderedDescending or NSOrderedAscending?

I'm not sure which object is ascending or descending from which object (if that makes sense).

share|improve this question
Wouldn't it be pretty simple to write it one way, run the comparison, and see if the order is what you expect? Easier than, say, posting the question and waiting for a response? –  mah Feb 14 '13 at 0:33
Yes but if I write it myself I can put it either way around. –  Fogmeister Feb 14 '13 at 0:34
How you place it is only meaningful when it's used, so if you use it, you'll have more than just an arbitrary decision (and enough to know if that decision was valid or opposite). If you were to place two Person objects in an NSArray, then sort the array using a comparison function that matches your guess, you would know immediately from the output if the elements were sorted according to your expectations (-> your decision was right), or contrary to them (-> reverse the sense of your comparison to fix it). –  mah Feb 14 '13 at 0:38
Alternatively you could look in the documentation for other classes that implement compare: (e.g. NSNumber) and see what they return. –  Sebastian Feb 14 '13 at 0:42
@Sebastian I did that before coming here. Seems people don't like it when you ask questions here... –  Fogmeister Feb 14 '13 at 0:49
add comment

2 Answers

up vote 2 down vote accepted

The result of:

[obj1 compare:obj2]

Should be:

  • NSOrderedAscending if when written as 'obj1, obj2' the objects are in ascending order;
  • NSOrderedDescending if when written as 'obj1, obj2' the objects are in descending order;
  • NSOrderedSame otherwise.

So you should see:

[@2 compare:@3] == NSOrderedAscending
[@"b" compare:@"a"] == NSOrderedDescending

etc. The way to remember it is to think about reading from left to right in whoever is doing the calling.

share|improve this answer
Excellent answer, thanks very much, this is exactly what I was looking for. –  Fogmeister Feb 14 '13 at 1:40
add comment

The easiest way is to just lean on existing implementations

- (NSComparisonResult)compare:(Person *)other;
  return [@(self.age) compare:@(other.age)];
share|improve this answer
add comment

Your Answer


