我可以根据密钥对NSDictionary
进行排序吗?
答案 0 :(得分:114)
您可以对键进行排序,然后通过迭代来创建NSMutableArray
。
NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys)
[sortedValues addObject: [dict objectForKey: key]];
答案 1 :(得分:1)
使用objectsForKeys:notFoundMarker:
来实现
NSDictionary *yourDictionary;
NSArray *sortedKeys = [yourDictionary.allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]];
// As we using same keys from dictionary, we can put any non-nil value for the notFoundMarker, because it will never used
NSArray *sortedValues = [yourDictionary objectsForKeys:sortedKeys notFoundMarker:@""];