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:... ] ;


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

I have a faulty Ajax call apparently

javascript php jquery sql ajax

I have a project where a user can have his own VirtualDiary online. He/She registers logs in and all that and is brought to a entry page with the date and a text area. The idea is that they will be...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.