在我的plist文件中访问两个级别

时间:2011-08-30 04:16:43

标签: xcode plist

我有一个包含国家,州,城市的plist文件。我可以访问国家级别的采摘者,但我似乎无法得到州和城市填充。我创建了一个包含以下内容的plist文件:country - >字典,州 - >字典和城市 - >阵列。

代码是:

NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"placesdictionary" ofType:@"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.places = dictionary;
NSArray *componentsCountry = [self.places allKeys];
NSArray *sortedCountry = [componentsCountry sortedArrayUsingSelector:@selector(compare:)];
self.country = sortedCountry;
NSString *selectedCountry = [country objectAtIndex:0];

这很好。但是以下代码有错误:

NSArray *componentsState = [self.places allKeysForObject:selectedCountry];
NSArray *sortedState = [componentsState sortedArrayUsingSelector:@selector(compare:)];
self.state = sortedState;
NSString *selectedState = [state objectAtIndex:0];
NSArray *componentsCity = [self.places objectForKey:selectedState];
NSArray *sortedCity = [componentsCity sortedArrayUsingSelector:@selector(compare:)];
self.city = sortedCity;

你能帮我解决这些问题吗?谢谢。

这是我的plist文件:

    <?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>France</key>
        <dict>
            <key>state 3</key>
            <array>
                <string>Paris</string>
            </array>
            <key>state 2</key>
            <array>
                <string>Nice</string>
            </array>
        </dict>
        <key>US</key>
        <dict>
            <key>california</key>
            <array>
                <string>LA</string>
                <string>San Fran</string>
                <string>San Diego</string>
            </array>
            <key>new jersey</key>
            <array>
                <string>riverdale</string>
                <string>newark</string>
                </array>
        </dict>
     </dict>
    </plist>

1 个答案:

答案 0 :(得分:0)

我建议使用这样的代码来访问plist数据:

NSString *errorDesc = nil;
NSPropertyListFormat format;
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:[[NSBundle mainBundle] pathForResource:@"placesdictionary" ofType:@"plist"]];
NSMutableDictionary *properties = (NSMutableDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
NSDictionary *france = (NSDictionary *)[properties valueForKey:@"France"]; 
// if cities is in countries then you can access them using [countries valueForKey:@"cityName"];
NSArray *cities = [france valueForKey:@"state 3"];