0

here I try to sort a NSdictionary key and a value I find a method but it does not work.

[detailEvent[@"occurences"] sortUsingSelector : @selector(compare:)];

here is the source sorted

"occurences": [
    {
      "jour": "2014-07-27T00:00:00.000Z",
      "hour_start": "11:00:00",
      "hour_end": "18:00:00"
    },
    {
      "jour": "2014-07-26T00:00:00.000Z",
      "hour_start": "11:00:00",
      "hour_end": "18:00:00"
    },
    {
      "jour": "2014-07-25T00:00:00.000Z",
      "hour_start": "11:00:00",
      "hour_end": "18:00:00"
    }

I do not add all because it is very long

I want sorted by date so the key jour

is that there is another method to sort the dictionary?

thanks

user1774481
  • 193
  • 3
  • 12
  • 1
    This is a good example of a bad question my friend. You have to supply more info about how the compare function looks etc. Otherwise it's hard to help you. – Widerberg Apr 02 '14 at 08:46
  • 2
    Presumably the values for `jour` in your dictionaries are `NSString` instances? And you want to compare them as dates. So, you need to convert them. – Wain Apr 02 '14 at 08:50
  • 1
    http://stackoverflow.com/questions/9708742/getting-nsdictionary-keys-sorted-by-their-respective-values – Kumar KL Apr 02 '14 at 08:52

1 Answers1

2

I believe that this will sort the dictionaries correctly

    NSArray *sorted = [detailEvent[@"occurences"] sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *d1, NSDictionary *d2)
    {
        NSString *s1 = d1[@"jour"];
        NSString *s2 = d2[@"jour"];

        return( [s1 compare:s2] );
    }];

If you want them sorted so the most recent date is first, then change the order of the compare

        return( [s2 compare:s1] );
user3386109
  • 34,287
  • 7
  • 49
  • 68
  • nope, values of jour are strings, you first have to convert them into nsdate objects – Eugene Apr 02 '14 at 09:08
  • 2
    Yes @Eugene they are strings, strings that have a 4-digit year followed by a 2-digit month, followed by a 2-digit day, so in fact they will sort correctly as strings, and do not need to be converted to dates. – user3386109 Apr 02 '14 at 09:12
  • You can be a bit neater by changing the signature of the block to `^(NSDictionary *d1, NSDictionary *d2)` which saves doing the assignment at the top of the block. – Abizern Apr 02 '14 at 09:35
  • @Abizern thanks for the tip. I guess I've been over-trained by `qsort` which is extremely picky about the function prototype. – user3386109 Apr 02 '14 at 09:40
  • In this case you aren't changing the prototype, you're just being more specific. The objects being passed are going to be dictionaries, you know that because it's your code. The block takes the actual objects but declares them to be `id` you're free to be more specific. – Abizern Apr 02 '14 at 09:41