Sorting NSDictionary

﹥>﹥吖頭↗ 提交于 2019-11-26 23:10:40

问题


I was wondering if someone can show me how to sort an NSDictionary; I want to read it starting from the last entry, since the key is Date + Time and I want to be able to append it to an NSMutableString. I was able to read it using an enumerator but I don't get the results I want.

Thanks


回答1:


For your requirements the easiest way is to create a new array from the keys, sort that, then use the array to reference items from the original dictionary.

(Note myComparison is your own method that will compare two keys).

NSMutableArray* tempArray = [NSMutableArray arrayWithArray:[myDict allKeys]]; 
[tempArray sortedArrayUsingSelector:@selector(myComparison:)];

for (Foo* f in tempArray)
{
  Value* val = [myDict objectForKey:f];
}



回答2:


I've aggregated some of the other suggestions on StackOverflow on sorting an NSDictionary into something very compact that will sort alphabetically. I have a Plist file in 'path' that I load in to memory and want to dump.

NSDictionary    *glossary = [NSDictionary dictionaryWithContentsOfFile: path];
NSArray         *array1 = [[glossary allKeys] sortedArrayUsingDescriptors:@[ [NSSortDescriptor  sortDescriptorWithKey:@"" ascending:YES selector:@selector(localizedStandardCompare:)] ]];
for ( int i=0; i<array1.count; i++)
{
    NSString* key = [array1 objectAtIndex:i];
    NSString* value = [glossary objectForKey:key];
    NSLog(@"Key=%@, Value=%@", key, value );
}


来源:https://stackoverflow.com/questions/2256966/sorting-nsdictionary

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