我有一个NSArray包含这样的日期字符串(即 NSString):“Thu, 21 May 09 19:10:09 -0700”
我需要NSArray按日期排序。我考虑过先将日期字符串转换为NSDate对象,但在如何按对象排序时被困在那里NSDate。
谢谢。
我有一个NSArray包含这样的日期字符串(即 NSString):“Thu, 21 May 09 19:10:09 -0700”
我需要NSArray按日期排序。我考虑过先将日期字符串转换为NSDate对象,但在如何按对象排序时被困在那里NSDate。
谢谢。
如果我有一个NSMutableArray类型为“beginDate”的对象,NSDate我正在使用NSSortDescriptor如下:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
将日期作为NSDate对象存储在 NS(Mutable)Array 中,然后使用-[NSArray sortedArrayUsingSelector:或作为参数-[NSMutableArray sortUsingSelector:]传递。@selector(compare:)该-[NSDate compare:]方法将为您按升序排列日期。这比创建一个NSSortDescriptor更简单,也比编写自己的比较函数简单得多。(NSDate对象知道如何相互比较,至少与我们希望使用自定义代码完成的效率一样。)
您也可以使用以下内容:
//Sort the array of items by date
[self.items sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
return [obj2.date compare:obj1.date];
}];
但这确实假设日期存储为 aNSDate而 aNString,这应该是没有问题的。最好,我建议还以原始格式存储数据。在这种情况下更容易操作。
您可以使用块进行就地排序:
sortedDatesArray = [[unsortedDatesArray sortedArrayUsingComparator: ^(id a, id b) {
NSDate *d1 = [NSDate dateWithString: s1];
NSDate *d2 = [NSDate dateWithString: s2];
return [d1 compare: d2];
}];
我建议您在排序之前将所有字符串转换为日期,以免转换次数超过日期项。任何排序算法都会为您提供比数组中的项目数更多的字符串到日期转换(有时更多)
关于块排序的更多信息:http: //sokol8.blogspot.com/2011/04/sorting-nsarray-with-blocks.html
您可以使用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];
使用 aNSMutableArray时,您可以sortArrayUsingFunction:context:改用。
在我的情况下,它的作用如下:
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];
返回[d1比较:d2];
}];
我有一本字典,其中所有键的日期格式为 dd-MM-yyyy。allKeys 返回未排序的字典键,我想按时间顺序显示数据。
Once you have an NSDate, you can create an NSSortDescriptor with initWithKey:ascending: and then use sortedArrayUsingDescriptors: to do the sorting.
斯威夫特 3.0
myMutableArray = myMutableArray.sorted(by: { $0.date.compare($1.date) == ComparisonResult.orderedAscending })
改变这个
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
至
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Date" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
只需更改 KEY:它必须Date始终