简体   繁体   English

对日期字符串或对象的NSArray进行排序

[英]Sort NSArray of date strings or objects

I have an NSArray that contains date strings (ie NSString) like this: "Thu, 21 May 09 19:10:09 -0700" 我有一个包含日期字符串(即NSString)NSArray ,如下所示:“星期四,2009年5月21日19:10:09 -0700”

I need to sort the NSArray by date. 我需要按日期对NSArray进行排序。 I thought about converting the date string to an NSDate object first, but got stuck there on how to sort by the NSDate object. 我想过首先将日期字符串转换为NSDate对象,但是如何按NSDate对象进行排序则陷入困境。

Thanks. 谢谢。

If I have an NSMutableArray of objects with a field "beginDate" of type NSDate I am using an NSSortDescriptor as below: 如果我有一个NSMutableArray每个对象都有一个域“BEGINDATE”型NSDate我使用的是NSSortDescriptor如下:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];

Store the dates as NSDate objects in an NS(Mutable)Array, then use -[NSArray sortedArrayUsingSelector: or -[NSMutableArray sortUsingSelector:] and pass @selector(compare:) as the parameter. 将日期作为NSDate对象存储在NS(Mutable)数组中,然后使用-[NSArray sortedArrayUsingSelector:-[NSMutableArray sortUsingSelector:]并传递@selector(compare:)作为参数。 The -[NSDate compare:] method will order dates in ascending order for you. -[NSDate compare:]方法将按升序为您排序日期。 This is simpler than creating an NSSortDescriptor , and much simpler than writing your own comparison function. 这比创建NSSortDescriptor简单,并且比编写自己的比较函数简单得多。 ( NSDate objects know how to compare themselves to each other at least as efficiently as we could hope to accomplish with custom code.) NSDate对象知道如何将自己相互比较,至少与我们希望使用自定义代码一样有效。)

You may also use something like the following: 您还可以使用以下内容:

//Sort the array of items by  date
    [self.items sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return [obj2.date compare:obj1.date];
    }];

But this does assume that the date is stored as a NSDate rather a NString , which should be no problem to make/do. 但这确实假设日期存储为NSDate而不是NString ,这应该没有问题。 Preferably, I recommend also storing the data in it's raw format. 我建议最好以原始格式存储数据。 Makes it easier to manipulate in situations like this. 在这种情况下更容易操作。

You can use blocks to sort in place: 您可以使用块进行排序:

sortedDatesArray = [[unsortedDatesArray sortedArrayUsingComparator: ^(id a, id b) {
    NSDate *d1 = [NSDate dateWithString: s1];
    NSDate *d2 = [NSDate dateWithString: s2];
    return [d1 compare: d2];
}];

I suggest you convert all your strings to dates before sorting not to do the conversion more times than there are date items. 我建议您在排序之前将所有字符串转换为日期,而不是比日期项更多次地进行转换。 Any sorting algorithm will give you more string to date conversions than the number of items in the array (sometimes substantially more) 任何排序算法都会为您提供更多的字符串到日期转换,而不是数组中的项目数(有时更多)

a bit more on blocks sorting: http://sokol8.blogspot.com/2011/04/sorting-nsarray-with-blocks.html 关于块排序的更多内容: http//sokol8.blogspot.com/2011/04/sorting-nsarray-with-blocks.html

You can use sortedArrayUsingFunction:context: . 您可以使用sortedArrayUsingFunction:context: . Here is a sample: 这是一个示例:

NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {
    NSDate *d1 = [NSDate dateWithString:s1];
    NSDate *d2 = [NSDate dateWithString:s2];
    return [d1 compare:d2];
}

NSArray *sorted = [unsorted sortedArrayUsingFunction:dateSort context:nil];

When using a NSMutableArray , you can use sortArrayUsingFunction:context: instead. 使用NSMutableArray ,可以使用sortArrayUsingFunction:context:代替。

What it worked in my case was the following: 在我的案例中它的作用如下:

NSArray *aUnsorted = [dataToDb allKeys];
    NSArray *arrKeys = [aUnsorted sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"dd-MM-yyyy"];
        NSDate *d1 = [df dateFromString:(NSString*) obj1];
        NSDate *d2 = [df dateFromString:(NSString*) obj2];
        return [d1 compare: d2];
    }];

I had a dictionary, where all keys where dates in format dd-MM-yyyy. 我有一本字典,其中所有键的日期格式为dd-MM-yyyy。 And allKeys returns the dictionary keys unsorted, and I wanted to present the data in chronological order. 并且allKeys返回未排序的字典键,我想按时间顺序显示数据。

获得NSDate ,可以使用initWithKey:ascending:创建NSSortDescriptor ,然后使用sortedArrayUsingDescriptors:进行排序。

Change this 改变这个

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];

To

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Date" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];

Just change the KEY: it must be Date always 只需更改KEY:它必须始终为Date

Swift 3.0

myMutableArray = myMutableArray.sorted(by: { $0.date.compare($1.date) == ComparisonResult.orderedAscending })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM