Objective-C:根据字典条目对NSDictionary的键进行排序 [英] Objective-C: Sort keys of NSDictionary based on dictionary entries
本文介绍了Objective-C:根据字典条目对NSDictionary的键进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,所以我知道字典无法排序。但是,假设我有 NSMutableArray * keys = [someDictionary allKeys];
现在,我想根据字典中的对应值(按字母顺序)对这些键进行排序。因此,如果字典包含 key = someString
,那么我想根据它们对应的字符串对键
进行排序。我认为它是 sortUsingComparator
的某些应用程序,但是在这一点上,我觉得有点超出我的能力。
OK so I know that dictionaries can't be sorted. But, say I have NSMutableArray *keys = [someDictionary allKeys];
Now, I want to sort those keys, based on the corresponding values in the dictionary (alphabetically). So if the dictionary contains key=someString
, then I want to sort keys
based on the strings they correspond to. I think its some application of sortUsingComparator
but its a little out of my reach at this point.
推荐答案
NSArray *keys = [someDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [someDictionary objectForKey:a];
NSString *second = [someDictionary objectForKey:b];
return [first compare:second];
}];
这篇关于Objective-C:根据字典条目对NSDictionary的键进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文