Is there an easy way of sorting a plist (array of dictionaries) by key value?

混江龙づ霸主 提交于 2019-12-07 12:41:51

问题


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.


回答1:


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



回答2:


I wrote a little Python script that reads from standard input and writes to standard output:

# sortplist.py
import plistlib
import sys

plist = plistlib.readPlist(sys.stdin)
plistlib.writePlist(plist, sys.stdout)

So, just do python sortplist.py <original.plist >sorted.plist.




回答3:


// 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...



回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/864412/is-there-an-easy-way-of-sorting-a-plist-array-of-dictionaries-by-key-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!