objective-c 对日期字符串或对象的 NSArray 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1132806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort NSArray of date strings or objects
提问by postalservice14
I have an NSArraythat contains date strings (i.e. NSString)like this: "Thu, 21 May 09 19:10:09 -0700"
我有一个NSArray包含这样的日期字符串(即 NSString):“Thu, 21 May 09 19:10:09 -0700”
I need to sort the NSArrayby date. I thought about converting the date string to an NSDateobject first, but got stuck there on how to sort by the NSDateobject.
我需要NSArray按日期排序。我想NSDate先将日期字符串转换为对象,但在如何按NSDate对象排序方面陷入困境。
Thanks.
谢谢。
回答by vinzenzweber
If I have an NSMutableArrayof objects with a field "beginDate" of type NSDateI am using an NSSortDescriptoras below:
如果我有一个NSMutableArray类型为“beginDate”的对象,NSDate我将使用NSSortDescriptor如下所示的对象:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
回答by Quinn Taylor
Store the dates as NSDateobjects in an NS(Mutable)Array, then use -[NSArray sortedArrayUsingSelector:or -[NSMutableArray sortUsingSelector:]and pass @selector(compare:)as the parameter. The -[NSDate compare:]method will order dates in ascending order for you. This is simpler than creating an NSSortDescriptor, and much simpler than writing your own comparison function. (NSDateobjects know how to compare themselves to each other at least as efficiently as we could hope to accomplish with custom code.)
将日期作为NSDate对象存储在 NS(Mutable)Array 中,然后使用-[NSArray sortedArrayUsingSelector:or-[NSMutableArray sortUsingSelector:]并@selector(compare:)作为参数传递。该-[NSDate compare:]方法将为您按升序排列日期。这比创建NSSortDescriptor更简单,也比编写自己的比较函数简单得多。(NSDate对象知道如何相互比较,至少与我们希望用自定义代码完成的一样有效。)
回答by TheCodingArt
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 NSDaterather a NString, which should be no problem to make/do. Preferably, I recommend also storing the data in it's raw format. Makes it easier to manipulate in situations like this.
但这确实假设日期存储为NSDateaNString,这应该没有问题。最好,我还建议以原始格式存储数据。在这种情况下更容易操作。
回答by Kostiantyn Sokolinskyi
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
回答by notnoop
You can use sortedArrayUsingFunction:context:. Here is a sample:
您可以使用sortedArrayUsingFunction:context:. 这是一个示例:
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.
使用 a 时NSMutableArray,可以sortArrayUsingFunction:context:改用。
回答by Javier Calatrava Llavería
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. And allKeys returns the dictionary keys unsorted, and I wanted to present the data in chronological order.
我有一本字典,其中所有键的日期格式为 dd-MM-yyyy。allKeys 返回未排序的字典键,我想按时间顺序显示数据。
回答by smorgan
Once you have an NSDate, you can create an NSSortDescriptorwith initWithKey:ascending:and then use sortedArrayUsingDescriptors:to do the sorting.
一旦有了NSDate,您就可以创建一个NSSortDescriptorwith initWithKey:ascending:,然后使用它sortedArrayUsingDescriptors:来进行排序。
回答by user2339385
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 Datealways
只需更改 KEY:它必须Date始终
回答by Abhishek Jain
Swift 3.0
斯威夫特 3.0
myMutableArray = myMutableArray.sorted(by: { ##代码##.date.compare(.date) == ComparisonResult.orderedAscending })

