David Casillas
David Casillas

Reputation: 1911

Order NSArray of custom objects based in an attribute of type NSDate

I have a NSArray of AEMEvent custom objects. One of the properties of this AEMEvent class is startDate of type NSDate.

@interface AEMEvent : NSObject
{
    //.....
    NSDate *startDate;
    //..........
}

I would like to sort this array based on this property, so the output will be an NSArray full of AEMEvent objects ordered by startDate attribute.

I have seen this interesting answer for sorting an NSArray of NSDate objects using -[NSArray sortedArrayUsingSelector: or -[NSMutableArray sortUsingSelector:] and passing @selector(compare:)as parameter and wonder if there will be a way to use this in my situation - Sort NSArray of date strings or objects

Upvotes: 0

Views: 242

Answers (1)

Ecarrion
Ecarrion

Reputation: 4950

// Sort AMEvent by startDate 

NSSortDescriptor * firstDescriptor = [[[NSSortDescriptor alloc] 
                                       initWithKey:@"startDate" ascending:YES 
                                       selector:@selector(caseInsensitiveCompare:)]

NSArray * descriptors = [NSArray arrayWithObjects:firstDescriptor, nil];  
NSArray * sortedArray = [yourArray sortedArrayUsingDescriptors:descriptors];

Upvotes: 1

Related Questions