matrix4use
matrix4use

Reputation: 631

How to: sort NSArray by date in descending order with nil date left on top of result set

I have the following method where self.orderHeader.meetings is a core data NSManagedObject with meetings being a list of metting. The method sorts the meetings by date (meetingDate):

- (NSArray *)sortMeetingList {
    return [[self.orderHeader.meetings allObjects] sortedArrayUsingDescriptors: [NSArray arrayWithObject: [NSSortDescriptor sortDescriptorWithKey:@"meetingDate" ascending:NO]]];
}

It returns what I want except for meeting objects that do not have a meetingDate set. These are left at the bottom of the list, but (given the descending order) I would like to have them shown on top of the list:

So for example: [nil, 2014-12-29, 2014-12-24] instead of [2014-12-29, 2014-12-24, nil]

Is there an easy way to do this ??

Upvotes: 0

Views: 376

Answers (3)

Leszek Szary
Leszek Szary

Reputation: 10328

Try something like this:

NSArray *sortedMeetings = [unsortedMeetings sortedArrayUsingComparator:^NSComparisonResult(MeetingObjectClass *obj1, MeetingObjectClass *obj2) {
    if (!obj1.meetingDate)
        return NSOrderedAscending;
    if (!obj2.meetingDate)
        return NSOrderedDescending;
    return [obj2.meetingDate compare:obj1.meetingDate];
}];

Upvotes: 4

Wain
Wain

Reputation: 119031

Use a different approach to sorting so that you can explicitly specify how to deal with each comparison, such as by using sortedArrayUsingFunction:context:.

Upvotes: 0

rocky
rocky

Reputation: 3541

You can possibly replace the nil dates with [NSDate distantFuture]

Upvotes: 0

Related Questions