Reputation: 24902
I noticed that NSString
understands the message compare:
but I couldn't fin much info about the generic mechanism of comparing objects in Cocoa. What classes implement compare:
? Is this some sort of protocol
?
I need this to implement something similar to Smalltalk's
OrderedCollection
: an array that is always kept sorted.
Thanks advance!
Upvotes: 0
Views: 82
Reputation: 71008
You're on the right track that compare:
is present on some classes and is used for sorting, but it's not a standard part of any protocol. (-isEqual:
on the other hand, is required by NSObject
and thus exists on nearly everything.)
You can sort a collection by telling the collection to sort its contents via the compare:
method on each item:
[myMutableArray sortUsingSelector:@selector(compare:)];
If you implement a comparison method on your own classes, then it should accept an object of the same class, and return NSOrderedAscending
, NSOrderedDescending
, or NSOrderedSame
as appropriate.
The method's existence isn't standardized because its semantics can't really be standardized. Many objects can be "compared" in multiple ways, depending on what you want. Even strings have both a compare:
and a caseInsensitiveCompare:
and lots of other locale-dependent options, depending on what you're trying to achieve.
All this said, use compare:
when it works for you, but it dates back to early ObjC and there are also block-based mechanisms to use for sorting in many of the custom comparison cases that you might find simpler.
Upvotes: 2