1

I have a dico NSDictionary containing things like: { 123 = , 125 = , ... 73 = }

123, 125, .., 73 are NSString.

I'd like to have an NSArray containing the objects ordered by their id:

[ <MyObject:73>, <MyObject:123>, ..., <MyObject:125> ]

What is the most efficient way to do so ?

I used [[dico allKeys] sortedArrayUsingSelector:@selector(compare:)] to key a list of ordered keys but as the keys are NSString they are not ordered the right way (I could end up with [ 42, 46, 5, 56. ...].

taskinoor
  • 45,586
  • 12
  • 116
  • 142
Luc
  • 16,604
  • 34
  • 121
  • 183

2 Answers2

1

When sorting NSStrings that represent numbers you want to use the NSNumericSearch option to sort them like numbers, e.g. 1 < 20 < 100 < 1000. Here's an example:

    NSMutableDictionary* d = [NSMutableDictionary dictionaryWithCapacity:3];
    [d setObject:@"C" forKey:@"3"];
    [d setObject:@"A" forKey:@"1"];
    [d setObject:@"B" forKey:@"2"];

    NSArray* sortedKeys = [d keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];

    NSLog(@"%@",sortedKeys);

    NSArray* sortedObjs = [d objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];
    NSLog(@"%@", sortedObjs);
Mike Katz
  • 2,060
  • 2
  • 17
  • 25
0

You could use the keysSortedWithCompartor method of your NSDictionary, where you can supply a comparator to compare the keys whatever way you wish (in your case, by comparing them as integers).

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • what is the exact signature of this method ? I do not find it in apple documentation. – Luc Jan 09 '12 at 15:27