【问题标题】:How to sort array of dictionaries by date using sort descriptor如何使用排序描述符按日期对字典数组进行排序
【发布时间】:2016-05-25 09:41:09
【问题描述】:

我有一个字典数组,其中字典是这样的。

Rows = (
    "<DriverRowRecord: 0x7f8de3a240d0>",
    "<DriverRowRecord: 0x7f8de3a18790>"
);
Sections = "<DriverSectionRecord: 0x7f8de3a2c5a0>";

这里DriverRowRecordDriverSectionRecord 是不同的类。在DriverSectionRecord 我有一个date 属性。

@interface DriverSectionRecord : NSObject
    @property(nonatomic,retain)NSDate *date;
@end

现在我想根据DriverSectionRecorddate 属性对数组进行排序。如果字典包含 date 键,我会这样排序。

  NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
  NSArray *descriptors = [NSArray arrayWithObject:descriptor];
  NSArray *Ascendingorder = [Array sortedArrayUsingDescriptors:descriptors];

但是,它不起作用,因为 dateDriverSectionRecord 的属性。我怎样才能做到这一点?

【问题讨论】:

  • 您想根据单个DriverSectionRecord 属性对Rows 进行排序吗?什么?
  • Sections.date? (如果“Sections”确实是 DriverSectionRecord 值的键,区分大小写。)
  • 在我的字典数组中,每个字典都包含有日期的“DriverSectionRecord”。我想根据那个日期排序。重要的是我的字典中没有“日期”键。
  • @Larme,哇,“Sections.date”是 wrkng。我想像“Sections.DriverSectionRecord.date”。你能以任何方式向我解释后台进程是如何工作的。我的意思是即使部分直接没有日期属性。
  • KVC/valueForKeyPath: 相关(“KVC”实际上是其背后的真正关键字,但valueForKeyPath: 可能会给您示例结果)。如果您查看 initWitKey:ascending: 的文档并阅读 key 参数,您会得到什么。

标签: ios objective-c nsarray nsdate nssortdescriptor


【解决方案1】:
 NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"Sections.date" ascending:YES];
 NSArray *descriptors = [NSArray arrayWithObject:descriptor];
 NSArray *Ascendingorder = [Array sortedArrayUsingDescriptors:descriptors];

我从上面的 cmets 得到了他的解决方案。感谢大家提供如此出色的说明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 2019-12-07
    • 1970-01-01
    相关资源
    最近更新 更多