对 NSDate 的 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSArray 有不同的排序方法,因为您可能需要不同的排序方式。 NSSortDescriptors 是一种通用方法,它为您提供了很多选项,包括在排序中使用哪些键、要在这些键上使用哪些选择器以及总体使用顺序等。或者您可以使用函数或比较器块来代替,如果您的情况需要这样做,或者这对您的具体情况是否更方便。
回答你的第一个问题,如果你希望今天是第一位,然后是昨天,那么,是的,这当然是降序。
要按降序对某些日期进行排序,您可以这样做:(假设一个充满 NSDates 的 NSArray 称为“dateArray”):
或者,如果您正在为 iOS 4+ 或 Snow Leopard+ 构建,您可以这样做:
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.
To sort some dates in descending order you can just do this: (assuming an NSArray full of NSDates called 'dateArray'):
Or, if you are building for iOS 4+ or Snow Leopard+ you can do this:
尝试这个魔术:
按升序对日期数组进行排序。
即日期越来越晚,或者换句话说,日期即将到来。
排序按降序排列的日期数组。(问题所问的内容)
即日期越来越早,日期进入过去,或者换句话说:今天在索引 0 处,昨天在索引 1 处。
Try this magic:
Sort array of dates in ascending order.
i.e. dates getting later and later, or to put it another way, dates going into the future.
Sort array of dates in descending order. (what the question asked)
i.e. dates getting earlier and earlier, dates going into the past or to put it another way: today is at index 0, yesterday at index 1.