sorting an NSArray of NSDates

夙愿已清 提交于 2019-12-18 15:12:09

问题


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?


回答1:


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'):

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

NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];

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
                                       }];



回答2:


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.

NSArray ascendingDates = [dates sortedArrayUsingSelector:@selector(compare:)];

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.

NSArray* descendingDates = [[[dates sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];


来源:https://stackoverflow.com/questions/4354753/sorting-an-nsarray-of-nsdates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!