简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM