How to reorder NSMutableDictionary to a NSMutableArray?

I have a NSMutableArray containing NSURLConnection descriptions, like so:

array {

    "<NSURLConnection: 0x60eb40>",
    "<NSURLConnection: 0x6030e0>",
    "<NSURLConnection: 0x602ce0>",
    "<NSURLConnection: 0x60c330>",
    "<NSURLConnection: 0x662f5a0>",
}

I have also a NSMutableDictionary whose keys are the items from the above NSMutableArray, like so:

dictionary {

"<NSURLConnection: 0x602ce0>"  = "Last update: Sep 3, 2012";
"<NSURLConnection: 0x6030e0>"  = "Last update: Sep 7, 2012";
"<NSURLConnection: 0x60c330>"  = "Last update: Sep 4, 2012";
"<NSURLConnection: 0x60eb40>"  = "Last update: Sep 6, 2012";
"<NSURLConnection: 0x662f5a0>" = "Last update: Sep 5, 2012";

}

I need to reorder the NSMutableDictionary to match the same order of the NSMutableArray indexes. Right now I'm doing like this:

int a;
for (a=0; a<self.array.count; a++) {

    NSString *key    = [self.array objectAtIndex:a];
    NSString *object = [self.dictionary objectForKey:key];

    if (object !=nil) {
        [self.array removeObjectAtIndex:a];
        [self.array insertObject:object atIndex:a];
    }
}

Is there a better way to reorder this NSMutableDicitioanry to match the order of the NSMutableArray ?

Thank you!

Answers


NSDictionary does not guarantee any ordering of it's key/value pairs. There's no way to keep your keys/values in a set order and it doesn't make sense for NSDictionary to work like this. (You use keys not indexes to retrieve values).

If you want your values or keys in a certain order for display purposes you can sort them after retrieving them:

NSArray * sortedKeys = [ [ myDictionary allKeys ] sortedArrayUsingSelector:... ] ;

or

NSArray * sortedKeys = [ [ myDictionary allKeys ] sortedArrayUsingComparator:... ] ;

You could then retrieve the associated objects for the sorted keys if you wanted.

Another option is to maintain 2 separate arrays, one for keys and one for values and keep them in order.


Need Your Help

Using QPainter over OpenGL in QGLWidget when using shaders

qt opengl overlay shader qpainter

Many of you Qt (4.6 specifically) users will be familiar with the Overpainting example supplied in the OpenGL tutorials, I'm trying to do something very similar but using shaders for the pure OpenGL