4

在我的应用程序中,我有一个部分从保存的 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);
    }
}

我想知道如何直接访问内部字典中的键值对,谁能给我一个正确的方向,好吗?

4

3 回答 3

3

这个怎么样:

NSString *blueColorString = [[savedData objectForKey:@"2"] objectForKey:@"color"];

诀窍是嵌套方法调用,第一个 [savedData objectForKey:2] 返回您可以再次调用该方法的内部字典对象。希望这能按预期工作。

最好的,罗宾

于 2010-01-16T20:31:35.733 回答
1

NSLog(@"%@", [savedData valueForKeyPath:@"1.color"]);

黄色

于 2010-01-16T22:38:40.313 回答
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]);
    }
}
于 2010-01-16T20:45:35.170 回答