Sort array of objects by their NSDate property

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?


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];

    NSSortDescriptor* sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"nsdatepropertyname" ascending:YES];
    [mutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortByDate]];

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

链接地址: http://www.djcxy.com/p/70808.html

上一篇: 使用其中一个键内的值对NSDictionaries数组进行排序

下一篇: 通过NSDate属性对对象数组进行排序