如何通过访问其NSDate属性对对象数组进行排序?
我知道可以使用[mutableArray sortUsingSelector:@selector(compare:)];
对日期数组进行排序,但是如何通过访问数组中每个元素的NSDate属性来按最早日期到最晚日期排序对象?
如何通过访问其NSDate属性对对象数组进行排序?
我知道可以使用[mutableArray sortUsingSelector:@selector(compare:)];
对日期数组进行排序,但是如何通过访问数组中每个元素的NSDate属性来按最早日期到最晚日期排序对象?
感谢所有回答,我找到了解决我的问题的答案。请查看NSGod的答案
以下是用户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]];
NSArray *sortedArray = [mutableArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSDate *first = [(Person*)a birthDate];
NSDate *second = [(Person*)b birthDate];
return [first compare:second];
}];
或者查看这个链接
您可以在自定义类中覆盖比较方法,以便比较两个自定义类对象,并根据对象上的日期返回适当的NSComparisonResult。
例如:
-(NSComparisonResult)compare:(YourClass*)otherObject
{
return [self.date compare:otherObject.date];
}
有一种方法叫做-[NSArray sortedArrayUsingComparator:]
。它接受一个块,在其中您可以实现任何适合您的对象的比较。
[mutableArray sortUsingDescriptors:@[sortByDate]];
- Mike SpraguesortUsingDescriptors:
会返回已排序的NSArray
。你可能想将其分配给另一个变量,并像Helium3的答案中所做的那样继续进行。 - Gabriel Osorio