对NSDictionary进行排序

6

我想知道如何对NSDictionary进行排序;我希望从最后一个条目开始读取,因为键是日期+时间,我想将其追加到NSMutableString中。我已经使用枚举器读取它,但没有得到想要的结果。

谢谢

2个回答

13

根据您的需求,最简单的方法是从键中创建一个新数组,对其进行排序,然后使用该数组引用原始字典中的项目。

(注意myComparison是您自己编写的比较两个键的方法)。

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

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

0

我已经汇总了StackOverflow上有关将NSDictionary排序为按字母顺序排序的非常紧凑的其他建议。 我有一个Plist文件在“路径”中,我将其加载到内存中并想要转储。

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 );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接