1

I have an array of dictionaries where dictionary is like this.

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

Here DriverRowRecord and DriverSectionRecord are separate classes. In DriverSectionRecord I have a date property.

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

Now I want to sort the array based on DriverSectionRecord's date property. If the dictionary contains the date key I sort it like this.

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

However, it doesn't work as date is a property of DriverSectionRecord. How can I achieve this?

Aleksander Azizi
  • 9,829
  • 9
  • 59
  • 87
siva krishna
  • 1,149
  • 2
  • 15
  • 23
  • You want to sort `Rows` based on a single `DriverSectionRecord` property? What? – trojanfoe May 25 '16 at 09:43
  • 1
    `Sections.date`? (if "Sections" is really the key for the `DriverSectionRecord` value, case sensitive.) – Larme May 25 '16 at 09:45
  • In my array of dictionaries, Each dictionary contains "DriverSectionRecord" which has date. I want to sort based on that date. The Important thing is I don't have a "date" key in my dictionary. – siva krishna May 25 '16 at 09:46
  • @Larme, Wow, "Sections.date" is wrkng. Im thinking like "Sections.DriverSectionRecord.date". Any way can you explain me background process how it worked. I mean Even though Sections Directly don't have date property. – siva krishna May 25 '16 at 09:54
  • KVC/`valueForKeyPath:` related (It's "KVC" in fact the real key-word behind that, but `valueForKeyPath:` may give you sample results). That what you'll get if you look at the documentation of `initWitKey:ascending:` reading the `key` parameter. – Larme May 25 '16 at 09:58
  • @Larme Can I acres that date property like "Sections.date".I mean will my date is printed for this code. NSLog(@"%@",[dic objectForKey:@"Sections.date"]); – siva krishna May 25 '16 at 10:04
  • @sivakrishna: You can't use `objectForKey:` because there is no object by that key, however, you can do `valueForKeyPath:` instead. A KVC key (or KVC keypath) is different to a dictionary's key. – dreamlax May 26 '16 at 04:50
  • @dreamlax Thanks for clearing my doubt. – siva krishna May 26 '16 at 04:53

1 Answers1

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

I got he solution from above comments. Thanks to all for such a great clarification.

siva krishna
  • 1,149
  • 2
  • 15
  • 23