Reputation: 77631
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.
i.e.
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).
Upvotes: 0
Views: 659
Reputation: 100622
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.
Upvotes: 2
Reputation: 38728
The easiest way is to just lean on existing implementations
- (NSComparisonResult)compare:(Person *)other;
{
return [@(self.age) compare:@(other.age)];
}
Upvotes: 2