[英]Sort Array of Dictionaries by NSDate
我有一系列字典。 在每个字典中,有一个关键的dateOfInfo
(一个NSDate
)和其他几个东西。 我想通过每个字典dateOfInfo
对数组进行排序,最新的是第一个结果。
我怎样才能做到这一点?
您可以使用NSSortDescription
进行排序,例如
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey: @"dateOfInfo" ascending: NO];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
您也可以使用该方法
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
基本的气泡排序算法可行。 在这种情况下,您需要循环遍历数组,在[array objectAtIndex:]上使用valueForKey消息来获取NSDate值。 对于比较日期,请参阅此帖子 。 因此,如果按日期的升序排序,只需将具有较低日期的对象(记住气泡排序比较?)添加到一个数组中,该数组将保存您的排序结果。
试试这样,
NSDateFormatter *fmtDate = [[NSDateFormatter alloc] init];
[fmtDate setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSComparator compareDates = ^(id string1, id string2)
{
NSDate *date1 = [fmtDate dateFromString:string1];
NSDate *date2 = [fmtDate dateFromString:string2];
return [date1 compare:date2];
};
NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"StartTime" ascending:YES comparator:compareDates];
[youArray sortUsingDescriptors:@[sortDesc1]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.