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

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

iphone - Plist Array to NSArray no objects

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

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

1 Answer

0 votes
by (71.8m points)

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"];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...