按照NSDate属性对对象数组进行排序

31

如何通过访问其NSDate属性对对象数组进行排序?

我知道可以使用[mutableArray sortUsingSelector:@selector(compare:)];对日期数组进行排序,但是如何通过访问数组中每个元素的NSDate属性来按最早日期到最晚日期排序对象?

可能重复:
如何按其自定义对象对NSMutableArray进行排序?

5个回答

35

感谢所有回答,我找到了解决我的问题的答案。请查看NSGod的答案

以下是用户NSGod提供的代码:

NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                 sortDescriptorWithKey:@"startDateTime" 
                                             ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedEventArray = [nodeEventArray
     sortedArrayUsingDescriptors:sortDescriptors];

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

2
为了让它更加简洁,你可以这样写第二行代码: [mutableArray sortUsingDescriptors:@[sortByDate]]; - Mike Sprague

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

或者查看这个链接


1

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

例如:

-(NSComparisonResult)compare:(YourClass*)otherObject
{
   return [self.date compare:otherObject.date];
}

1

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接