代码之家  ›  专栏  ›  技术社区  ›  suse

我可以根据Objective-C中的key对NSDictionary进行排序吗?

  •  43
  • suse  · 技术社区  · 14 年前

    我能把它分类吗 NSDictionary 基于密钥?

    2 回复  |  直到 12 年前
        1
  •  115
  •   Binarian    11 年前

    您可以对键进行排序,然后创建 NSMutableArray 通过迭代它们。

    NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];
    NSMutableArray *sortedValues = [NSMutableArray array];
    for (NSString *key in sortedKeys)
        [sortedValues addObject: [dict objectForKey: key]];
    
        2
  •  5
  •   Vitalii Gozhenko    9 年前

    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:@""];