Ios 通过索引获取NSDictionary键?
是否可以通过索引获取字典键 我正在尝试对选择器视图的数据源使用字典,并希望通过以下委托方法访问它:Ios 通过索引获取NSDictionary键?,ios,objective-c,ios7,nsdictionary,uipickerview,Ios,Objective C,Ios7,Nsdictionary,Uipickerview,是否可以通过索引获取字典键 我正在尝试对选择器视图的数据源使用字典,并希望通过以下委托方法访问它: - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{ if (component == 0){ return [NSString stringWithFormat:@"%@",[myDict // how to get
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if (component == 0){
return [NSString stringWithFormat:@"%@",[myDict // how to get the key]];
}
编辑--
myDict类似于:
项目1
- 分项目1
- 分项目2
- 分项目1
- 分项目2
section 1=所选section 0行(子项1,子项2)对应的myDict值否,因为字典没有顺序 除了字典之外,您还需要提供一个键数组,它将为您提供订单
@interface MyClass ()
@property NSMutableArray *keysArray; // Don't forget to allocate this in an init method
@end
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
if (component == 0){
NSString *key = self.keysArray[row];
return self.myDict[key]; // I assume you just want to return the value
}
...
由于
NSDictionary
是一个无序的关联容器,因此它没有索引的概念。它的密钥是任意排序的,这种顺序将来可能会改变
您可以从字典中获取键的NSArray
,并对其应用索引:
NSArray *keys = [myDict allKeys]; // Warning: this order may change.
但是,只有在字典保持不变的情况下,此索引方案才会保持一致:例如,如果使用NSMutableDictionary
,添加额外的键可能会更改现有键的顺序。这会导致极难调试的问题
更好的方法是将分拣员的物品放入一个有序的容器中,例如NSArray
。例如,为选择器项创建一个特殊类
@interface MyPickerItem : NSObject
@property (readwrite, nonatomic) NSString *item1;
@property (readwrite, nonatomic) NSString *item2;
@end
从字典中创建此类MyPickerItem
对象的NSArray
,按照您希望它们出现在picker视图中的方式对它们进行排序(例如,按item1
的字母顺序,然后按item2
的字母顺序),并使用NSArray
作为picker视图的数据源:
- (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->";
}
-(NSString*)pickerView:(UIPickerView*)pickerView titleForRow:(NSInteger)行forComponent:(NSInteger)component{
MyPickerItem*p=myArray[row];
开关(组件){
案例0:返回p.item1;
案例1:返回p.item2;
}
返回@”;
}
NSDictionary是一种无序的数据结构,这意味着使用索引进行访问没有多大意义。您可能需要一个NSArray
。但是,如果您的字典使用NSNumbers
作为键,那么您可以这样访问它
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if (component == 0) {
return [NSString stringWithFormat:@"%@", myDict[@(row)]];
}
}
这将为您提供随机排序的密钥
按索引获取字典键是什么意思?如何通过显示示例或更多代码来详细说明它?字典没有索引,您可以使用allKeys方法获取一个键数组。阅读NSDictionary规范,看看有哪些函数可用。+1获取有关分配
NSMutableDictionary
的提示。有多少次我因为忘记做那件事而把自己逼疯了…
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if (component == 0){
return [NSString stringWithFormat:@"%@",[myDict allKeys][row]];
}
}