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?

4

5 回答 5

35

感谢所有答案,我遇到了解决我问题的答案。检查 NSGod 的答案

这是感谢用户的代码:NSGod:

NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                 sortDescriptorWithKey:@"startDateTime" 
                                             ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedEventArray = [nodeEventArray
     sortedArrayUsingDescriptors:sortDescriptors];
于 2012-10-16T11:33:48.370 回答
14
    NSSortDescriptor* sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"nsdatepropertyname" ascending:YES];
    [mutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortByDate]];
于 2012-10-16T11:14:56.317 回答
10

您可以使用:

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

或者看这个链接

于 2012-10-16T11:14:14.630 回答
1

有一种方法叫做-[NSArray sortedArrayUsingComparator:]。它需要一个块,您可以在其中实现您认为适合您的对象的任何比较。

于 2012-10-16T11:15:22.743 回答
1

您可以覆盖自定义类中的 compare 方法,以便它比较自定义类的两个对象并根据对象上的日期返回适当的 NSComparisonResult。

例如:

-(NSComparisonResult)compare:(YourClass*)otherObject
{
   return [self.date compare:otherObject.date];
}
于 2012-10-16T11:12:48.907 回答