How to sort NSMutableArray of date objects

北城以北 提交于 2019-11-27 21:41:18
Anoop Vaidya

First you should convert all date Strings (which is NSString) objects to NSDate objects and then sort these dateObjects.

I believe you have dateArray containing all those strings.

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

OR

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

If your dates are really strings in the format YYYY-mm-dd, as in your question, then this will sort them in ascending order:

[arrayOfDates sortUsingSelector:@selector(compare:)];

That will also work if your dates are actually NSDate objects.

If you want to create a sorted copy of the array:

NSArray *sortedArray = [arrayOfDates sortedArrayUsingSelector:@selector(compare:)];

Sorting should be done, imo, by the database, in general. sqlite3 does support order by.

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