在我的应用程序中,我有一个部分,我从一个保存的plist加载,它有2个嵌套的词典,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>1</key>
<dict>
<key>color</key>
<string>yellow</string>
<key>lang</key>
<string>US</string>
<key>name</key>
<string>Peter</string>
<key>uid</key>
<string>1</string>
</dict>
<key>2</key>
<dict>
<key>color</key>
<string>blue</string>
<key>lang</key>
<string>US</string>
<key>name</key>
<string>Josh</string>
<key>uid</key>
<string>2</string>
</dict>
<key>3</key>
<dict>
<key>color</key>
<string>red</string>
<key>lang</key>
<string>DE</string>
<key>name</key>
<string>Susan</string>
<key>uid</key>
<string>3</string>
</dict>
</dict>
</plist>
现在我想要从键2访问类似外部字典的字符串,内部键颜色的值(蓝色) 我尝试制作2个循环,它适用于外部字典,但我无法访问内部
NSMutableDictionary *savedData = [NSMutableDictionary dictionaryWithContentsOfFile:path]; // This contains all data from plist
for (int x=0; x<[savedData count]; x++) {
NSString *itemNumber = [NSString stringWithFormat:@"%d", x+1];
//This prints out the correct inner dictionary
NSLog(@"item#%@: %@",itemNumber,[savedData objectForKey:itemNumber]);
for (NSDictionary *dict in [savedData objectForKey:itemNumber]) {
//prints out color, lang, uid, but no key-value pairs
NSLog(@"dict: %@",dict);
}
}
我想知道如何直接访问内部字典中的键值对,有人能给我一个正确的方向吗?
答案 0 :(得分:3)
这个怎么样:
NSString *blueColorString = [[savedData objectForKey:@"2"] objectForKey:@"color"];
诀窍是嵌套方法调用,第一个[savedData objectForKey:2]返回内部字典对象,您可以再次调用该方法。希望这可以按预期工作。
最佳, 罗宾
答案 1 :(得分:1)
NSLog(@"%@", [savedData valueForKeyPath:@"1.color"]);
黄
答案 2 :(得分:0)
通常,当您的键是字符串时,您将使用valueForKey:
:
// to get to "blue" string
NSLog(@"outer key '2', inner key 'color' = %@",[[savedData valueForKey:@"2"] valueForKey:@"color"]);
// all inner key / value pairs
for (NSString *key in savedData) {
NSDictionary *innerDict = [savedData valueForKey:key];
for (NSString *innerKey in innerDict) {
NSLog(@"key %@ value %@",innerKey,[innerDict valueForKey:innerKey]);
}
}