Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So I've searched, and read and have done this successfully before, but am running into a problem with this one.

I have a plist that is an array of strings. I get no objects being read into the array. I successfully do this for a dictionary in another controller. So here is my code.

    // Open plist and get brands
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"brands" ofType:@"plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:plistPath]) {
    NSLog(@"The file exists");
} else {
    NSLog(@"The file does not exist");
}

_brands = [NSArray arrayWithContentsOfFile:plistPath];

_catList = [[[NSMutableArray alloc] initWithCapacity:[_brands count]] autorelease];

and here is my plist. Note that the _brands array is defined as NSArray *brands, property set as nonatomic, readonly and is synthesized as brands = _brands.

<?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>Root</key>
    <array>
        <string>Brand A</string>
        <string>Brand B</string>
        <string>Brand C</string>
        <string>Brand D</string>
    </array>
</dict>
</plist>

I see that there is a tag, but in Xcode it shows as an array with strings. Not a dictionary>array>many strings

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
744 views
Welcome To Ask or Share your Answers For Others

1 Answer

PLists are dictionaries at their heart (notice the <dict> tag). Read the file into an NSDictionary, then ask the dictionary for the array using objectforKey: method and the Root key.

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:plistPath];
_brands = [dict objectForKey:@"Root"];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...