views:

1432

answers:

5

I need to reorder a plist (an array of dictonaries) by Key value.

In this example content I'd like to order by the value for the key Name (Matt, Joe):

<dict>
    <key>Name</key>
    <string>Matt</string>
    <key>Details</key>
    <string>Me</string>
</dict>
<dict>
    <key>Name</key>
    <string>Joe</string>
    <key>Details</key>
    <string>You</string>
</dict>

Is there an easy way? I don't want to do it in code each time the app is run, I just want to do it to the data file.

Any ideas?

Happy to use any tool to get this done: ninja parameters for sort on the command line, a plist editor, text editor or whatever.

+2  A: 
// Our key array
NSMutableArray *unsortedKeys = [NSMutableArray array];
// Assume we have some array of dictionaries
for( NSDictionary *dict in dictionaryArray ) {
  NSString *key = [dict objectForKey:@"Name"];
  if( key )
    [unsortedKeys addObject:key];
}
NSArray *sortedKeys = [unsortedKeys sortedArrayUsingSelector:@selector(compare:)];

// Do things with the keys...
Jason Coco
A: 

Python is your friend: http://effbot.org/zone/element-sort.htm :-)

Ramin
Thanks, I don't know Python though. :)
matt
You did mention ninjas, right? And then there's: http://xkcd.com/353/:-)
Ramin
Ramin, small world - I follow you on Twitter.
matt
+6  A: 

This is another coding solution, but it wouldn't be hard to make a basic command line tool that wrapped around it:

NSArray* arrayOfDictionaries; //the array we want to sort
NSSortDescriptor* nameSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES];
NSArray* sortedArray = [arrayOfDictionaries sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameSortDescriptor]];
[nameSortDescriptor release];
Brian Webster
Don't forget to release the sort descriptor after creating the array with it. The iPhone doesn't have GC.
Peter Hosey
Release added for great justice :)
Brian Webster
A: 

I ended up writing a five line PHP script to reorder them. I guess I still have a lot of Cocoa to learn before I can do something that quickly and comfortably with it.

Thanks for your answers.

matt
There's nothing wrong with using a script in this case, it's probably easier since you wouldn't have to create and build a project just for one task.
Marc Charbonneau
Exactly my thoughts, Marc.
matt
A: 

Hi Matt,

please share the php script you wrote to handle the sorting.

Thank you,

-FerrariX

FerrariX
Sorry, I no longer have it.
matt