简体   繁体   中英

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

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"];
NSString *plistPath = [self copyFileToDocumentDirectory:plistFileName];
NSDictionary *plistContents=[[NSDictionary alloc] initWithContentsOfFile:plistPath];

[plistPath release];
return  plistContents;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM