[英]iPhone Objects from NSDictionary PList
in my app I have a section where I load from a saved plist which has 2 nested dictionaries like this: 在我的应用程序中,我有一个部分,我从一个保存的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>
Now I want to access string like outer dictionary from key 2, value for inner key color (blue) I tried make 2 loops, and it works for the outer dictionary but I can't access the inner 现在我想从键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);
}
}
I'd like to know how to directly access key value pairs inside the inner dictionary, could anyone give me a kick in the right direction, please? 我想知道如何直接访问内部字典中的键值对,有人能给我一个正确的方向吗?
How about this: 这个怎么样:
NSString *blueColorString = [[savedData objectForKey:@"2"] objectForKey:@"color"];
The trick is to nest the method calls, the first one [savedData objectForKey:2] returns you the inner dictionary object on which you can call the method again. 诀窍是嵌套方法调用,第一个[savedData objectForKey:2]返回内部字典对象,您可以再次调用该方法。 Hope this works as intended.
希望这可以按预期工作。
Best, Robin 最好,罗宾
NSLog(@"%@", [savedData valueForKeyPath:@"1.color"]);
黄色
Typically, you would use valueForKey:
when your keys are strings: 通常,您将使用
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]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.