排序NSDates的NSArray [英] sorting an NSArray of NSDates

查看:135
本文介绍了排序NSDates的NSArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有NSDate对象的NSArray,我想对它们进行排序,使今天是0,昨天在1等。

I have an NSArray of NSDate objects and I want to sort them so that today is at 0, yesterday at 1 etc.

是升序还是降序,我使用一个函数,选择器或什么?

Is it ascending or descending, and do i use a function, selector or what?

推荐答案

NSArray有不同的排序方法,因为可能有不同的方式排序的东西。 NSSortDescriptors是一个通用的方法,为您提供了很多选项,在排序中使用什么键,什么选择器要使用这些键,以及总体顺序使用等等。或者你可以使用函数或比较器块,而不是如果

There are different sort methods for NSArray because there may be different ways you want to sort things. NSSortDescriptors are a general way that give you a lot of options as far as what keys to use in sorting, what selectors you want to use on those keys, and overall order to use, etc. Or you can use functions or comparator blocks instead if your case requires that or if that's more convenient for your particular case.

要回答你的第一个问题,如果你想今天是第一个,后面是昨天,那么,是的,

To answer your first question, if you want today to be first, followed by yesterday then, yes, that is of course descending order.

若要按降序排序某些日期,您只需执行以下操作:(假设NSArray中有一个名为dateArray的NSDate):

To sort some dates in descending order you can just do this: (assuming an NSArray full of NSDates called 'dateArray'):

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject: descriptor];
[descriptor release];

NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];

或者,如果你正在构建iOS 4+或Snow Leopard +,你可以这样做:

Or, if you are building for iOS 4+ or Snow Leopard+ you can do this:

NSArray *reverseOrderUsingComparator = [dateArray sortedArrayUsingComparator: 
                                       ^(id obj1, id obj2) {
                                           return [obj2 compare:obj1]; // note reversed comparison here
                                       }];

这篇关于排序NSDates的NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆