8

So I have a custom class Foo that has a number of members:

@interface Foo : NSObject {
    NSString *title;
    BOOL     taken;
    NSDate   *dateCreated;
}

And in another class I have an NSMutableArray containing a list of these objects. I would very much like to sort this array based on the dateCreated property; I understand I could write my own sorter for this (iterate the array and rearrange based on the date) but I was wondering if there was a proper Objective-C way of achieving this?

Some sort of sorting mechanism where I can provide the member variable to sort by would be great.

In C++ I used to overload the < = > operators and this allowed me to sort by object, but I have a funny feeling Objective-C might offer a nicer alternative?

Many thanks

davbryn
  • 7,156
  • 2
  • 24
  • 47

1 Answers1

15

That's quite simple to do.

First, in your Foo object, create a method

- (NSComparisonResult) compareWithAnotherFoo:(Foo*) anotherFoo;

Which will return

[[self dateCreated] compare:[anotherFoo dateCreated]];

In the end, call on the array

[yourArray sortUsingSelector:@selector(compareWithAnotherFoo:)];

Hope this helps, Paul

Pawel
  • 4,699
  • 1
  • 26
  • 26
  • Nice concise solution, though I had to change `compareWithDate` to `compare`. – davbryn May 06 '10 at 12:20
  • @Pawel This works fine but with characters as å ä ö the sorting is a bit off. (å and ä appears after a and ö after o). You don't happen to know how to solve this? – Groot Mar 24 '13 at 11:03
  • @Filip the order you have described seems to be fine as å and ä are just versions of letter a with diacritic marks added. What exactly is the behaviour you would expect? – Pawel Mar 24 '13 at 13:00
  • @Pawel Oh, sorry was in my own little swedish bubble, å ä ö appears after xyz in the swedish alphabet as ..xyzåäö. I managed to solve this using the following comparison method: - (NSComparisonResult) compareSongWithSong:(Song *)otherSong { return [[self title] compare:[otherSong title] options:NSCaseInsensitiveSearch range:NSMakeRange(0, self.title.length) locale:[[NSLocale alloc] initWithLocaleIdentifier:@"sv_SE"]]; } Hope it helps someone! – Groot Mar 24 '13 at 13:30