1

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

2 Answers 2

7

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"];
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I was going to go ahead and set it up as a dictionary, but I kept finding old tutorials and examples that read a plist directly into an array. Was this allowed in older iOS builds?
I don't know if it was ever allowed. I've always read them into Dictionaries.
I've come across a lot of examples like this one: iphonedevelopertips.com/data-file-management/…
3
NSString *plistPath = [self copyFileToDocumentDirectory:plistFileName];
NSDictionary *plistContents=[[NSDictionary alloc] initWithContentsOfFile:plistPath];

[plistPath release];
return  plistContents;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.