如何访问字典数组中的特定键值

时间:2011-03-09 19:14:40

标签: iphone ipad nsarray nsdictionary

如何从特定密钥访问单个密钥值?

我正在使用NSDictionary的NSArray和plist源,如下所示;

<plist version="1.0">
<array>
<dict>
    <key>name</key>
    <string>item name</string>
    <key>level</key>
    <integer>3</integer> // range is 1 .. 7
    <key>Stage1</key>
    <string>Text for Stage 1</string>
    <key>Stage2</key>
    <string>Text for Stage 2</string>
    <key>Stage3</key>
    <string>Text for Stage 3</string>
    <key>Stage4</key>
    <string>Text for Stage 4</string>
    <key>Stage5</key>
    <string>Text for Stage 5</string>
    <key>Stage6</key>
    <string>Text for Stage 6</string>
    <key>Stage7</key>
    <string>Text for Stage 7</string>
</dict>
// more dictionaries follow

我可以通过以下方式查看整个词典:

NSNumber *helps = [myArray objectAtIndex:[pickerView selectedRowInComponent:0]]; 
notesLabel.text = [NSString stringWithFormat:@"%@", helps];

非常感谢您的帮助......我是一个菜鸟。

直到,谢谢你的帮助!我能够添加:

NSDictionary *dictionary = [foodArray objectAtIndex:[pickerView selectedRowInComponent:0]];
notesLabel.text = (@"stage is: %@", [dictionary objectForKey:[NSString stringWithFormat:@"%@", stage]]);

这正是我所缺少的。 :)

1 个答案:

答案 0 :(得分:0)

查看NSDictionary上的文档 - 特别是“objectForKey:”

NSDictionary *dictionary = [myArray objectAtIndex:[pickerView selectedRowInComponent:0]];
NSLog(@"name: %@", [dictionary objectForKey:@"name"]);
NSLog(@"level: %@", [dictionary objectForKey:@"level"]);