Sorting NSDictionary

后端 未结 2 413
礼貌的吻别
礼貌的吻别 2020-12-06 03:04

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 b

相关标签:
2条回答
  • 2020-12-06 03:32

    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 );
    }
    
    0 讨论(0)
  • 2020-12-06 03:45

    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];
    }
    
    0 讨论(0)
提交回复
热议问题