31

Possible Duplicate:
How to sort an NSMutableArray with custom objects in it?

How does one sort an array of objects by accessing their NSDate properties?

I know one can use [mutableArray sortUsingSelector:@selector(compare:)]; on an array of dates, but how does one do it by accessing a NSDate property on each element in the array, sorting the objects by earliest date to latest date?

Community
  • 1
  • 1
some_id
  • 29,466
  • 62
  • 182
  • 304

5 Answers5

35

Thanks for all the answers, I came across this answer that solved my problem.Check NSGod's answer

Here is the code thanks to user: NSGod:

NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                 sortDescriptorWithKey:@"startDateTime" 
                                             ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedEventArray = [nodeEventArray
     sortedArrayUsingDescriptors:sortDescriptors];
Community
  • 1
  • 1
some_id
  • 29,466
  • 62
  • 182
  • 304
14
    NSSortDescriptor* sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"nsdatepropertyname" ascending:YES];
    [mutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortByDate]];
Thomas
  • 649
  • 9
  • 17
  • 2
    To make it slightly more concise, you could write the second line like this: `[mutableArray sortUsingDescriptors:@[sortByDate]];` – Mike Sprague May 19 '14 at 22:21
  • 2
    To clarify a bit more (if needed), `sortUsingDescriptors:` returns the sorted `NSArray`. You'll probably want to assign that to another variable and take it from there as done on [Helium3's answer](http://stackoverflow.com/a/12913805/2192331). – Gabriel Osorio Sep 11 '14 at 16:16
9

You can use:

   NSArray *sortedArray = [mutableArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        NSDate *first = [(Person*)a birthDate];
        NSDate *second = [(Person*)b birthDate];
        return [first compare:second];
    }];

Or see this link

Community
  • 1
  • 1
Daniel
  • 577
  • 2
  • 12
1

You can override the compare method in your custom class so that it compares two objects of your custom class and returns the appropriate NSComparisonResult according to the dates on the objects.

Eg:

-(NSComparisonResult)compare:(YourClass*)otherObject
{
   return [self.date compare:otherObject.date];
}
Samhan Salahuddin
  • 2,140
  • 1
  • 17
  • 24
1

There is a method called -[NSArray sortedArrayUsingComparator:]. It takes a block in which you can implement any comparison you see fit for your objects.

waldrumpus
  • 2,540
  • 18
  • 44