通过索引获取NSDictionary键?

Sam*_*her 10 objective-c nsdictionary uipickerview ios ios7

是否可以通过索引获取字典键?

我正在尝试使用字典作为选择器视图的数据源,并希望在以下委托方法中访问它:

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if (component == 0){
   return  [NSString stringWithFormat:@"%@",[myDict // how to get the key]];
}
Run Code Online (Sandbox Code Playgroud)

编辑 -

myDict是这样的:

第1项

  • 子项目1
  • 子项目2

第2项

  • 子项目1
  • 子项目2

我想使用myDict作为具有2个部分的选择器视图的数据源:

第0节= myDict键(第1项,第2项)

第1部分=所选第0行的相应myDict值(子项1,子项2)

das*_*ght 21

由于NSDictionary是一个无序的关联容器,它没有索引的概念.它的密钥是任意订购的,该订单将来可能会发生变化.

您可以NSArray从字典中获取密钥,并对其应用索引:

NSArray *keys = [myDict allKeys]; // Warning: this order may change.
Run Code Online (Sandbox Code Playgroud)

但是,只要字典保持不变,此索引方案就会保持一致:例如,如果使用NSMutableDictionary,添加额外的键可能会更改现有键的顺序.这导致极难调试的问题.

更好的方法是将拾取器的物品放入有序的容器中,例如NSArray.例如,为选取器项创建一个特殊类

@interface MyPickerItem : NSObject
@property (readwrite, nonatomic) NSString *item1;
@property (readwrite, nonatomic) NSString *item2;
@end
Run Code Online (Sandbox Code Playgroud)

从您的字典中创建一个NSArray这样的MyPickerItem对象,按照您希望它们在选择器视图中显示的方式(按字母顺序排列item1,然后按顺序item2)对它们进行排序,并将其NSArray用作选择器视图的数据源:

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    MyPickerItem *p = myArray[row];
    switch (component) {
        case 0: return p.item1;
        case 1: return p.item2;
    }
    return @"<-ERROR->";
}
Run Code Online (Sandbox Code Playgroud)